Skip to content

Instantly share code, notes, and snippets.

@myndzi
Created December 31, 2014 04:54
Show Gist options
  • Save myndzi/e233c1d136a4be23f06f to your computer and use it in GitHub Desktop.
Save myndzi/e233c1d136a4be23f06f to your computer and use it in GitHub Desktop.
var toServer = csp.chan();
var throttled = throttle(toServer);
csp.go(function* () {
var msg;
while (true) {
msg = yield csp.take(toServer);
if (msg === csp.CLOSED) { return; }
console.log(msg);
}
});
csp.go(function* () {
for (var i = 0; i < 10; i++) {
yield csp.put(throttled, 'foo ' + i);
}
});
function throttle(outCh, opts) {
opts = opts || { };
var delay = opts.hasOwnProperty('delay') ? opts.delay : 2000,
burstLines = opts.hasOwnProperty('burstLines') ? opts.burstLines : 5,
burst = opts.hasOwnProperty('burst') ? opts.burst : burstLines * delay,
limit = opts.hasOwnProperty('limit') ? opts.limit : 10,
nextMessage = Date.now();
var inCh = csp.chan(csp.buffers.dropping(limit));
csp.go(function* () {
while (true) {
var msg = yield csp.take(inCh);
if (msg === csp.CLOSED) {
outCh.close();
return;
}
var now = Date.now();
if (nextMessage < now) { nextMessage = now; }
nextMessage += delay;
if (nextMessage >= now + burst) {
yield csp.timeout(nextMessage - now - burst);
}
csp.put(outCh, msg);
}
});
return inCh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment