Skip to content

Instantly share code, notes, and snippets.

@nicolashery nicolashery/throttle.js
Last active Aug 29, 2015

Embed
What would you like to do?
Throttle a channel in js-csp
// https://github.com/jlongster/js-csp
// Throttle ported from:
// https://gist.github.com/swannodette/5886048
var csp = require('js-csp');
var chan = csp.chan;
var go = csp.go;
var put = csp.put;
var take = csp.take;
var timeout = csp.timeout;
function listen(el, type, ch) {
ch = ch || chan();
el.addEventListener(type, function(e) {
csp.putAsync(ch, e);
});
return ch;
}
function throttle(inCh, ms) {
var outCh = chan();
go(function*() {
while(true) {
yield put(outCh, yield take(inCh));
yield take(timeout(ms));
}
});
return outCh;
}
go(function*() {
var el = document.getElementById('location');
// Important that the source channel `ch` be a sliding buffer of size 1
var ch = listen(el, 'mousemove', chan(csp.buffers.sliding(1)));
var throttledCh = throttle(ch, 500);
while(true) {
var e = yield take(throttledCh);
el.innerHTML = ((e.layerX || e.clientX) + ', ' +
(e.layerY || e.clientY));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.