Skip to content

Instantly share code, notes, and snippets.

@nicolashery
Last active August 29, 2015 14:06
Show Gist options
  • Save nicolashery/351d803991face794165 to your computer and use it in GitHub Desktop.
Save nicolashery/351d803991face794165 to your computer and use it in GitHub Desktop.
(deprecated) Throttling key presses in JavaScript CSP
function bindKey(key, ch) {
ch = ch || chan();
Mousetrap.bind(key, function() {
console.log('[keyCh]', 'key', key);
csp.putAsync(ch, key);
});
return ch;
}
function tickChan() {
var ch = chan(csp.buffers.sliding(1));
var t = 0;
go(function*() {
while(yield put(ch, t)) {
t = t + 1;
console.log('tick', t);
yield take(timeout(3000));
}
});
return ch;
}
function spaceChan() {
var ch = chan();
var tickCh = tickChan();
// This doesn't seem to work, I'm still getting key events after the tick
var keyCh = bindKey('space', chan(csp.buffers.dropping(0)));
go(function*() {
var t;
var key;
var open = true;
while(open) {
// NOTE: trying to throttle key presses by tick,
// have no idea what I'm doing :)
key = yield take(keyCh);
t = yield take(tickCh);
open = yield put(ch, key);
console.log('[spaceCh]', 'put key', key, 'on tick', t);
if (!open) {
keyCh.close();
tickCh.close();
}
}
});
return ch;
}
function main() {
var spaceCh = spaceChan();
go(function*() {
var count;
while(true) {
key = yield take(spaceCh);
console.log('[main]', 'got key', key);
}
});
}
main();
tick 1
tick 2
[keyCh] key space
[spaceCh] put key space on tick 1
[main] got key space
[keyCh] key space
[keyCh] key space
[keyCh] key space
[keyCh] key space
[keyCh] key space
[keyCh] key space
tick 3
[spaceCh] put key space on tick 2
[main] got key space
tick 4
tick 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment