Skip to content

Instantly share code, notes, and snippets.

@nicolashery
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolashery/9414d2357258718891e3 to your computer and use it in GitHub Desktop.
Save nicolashery/9414d2357258718891e3 to your computer and use it in GitHub Desktop.
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