Skip to content

Instantly share code, notes, and snippets.

@kriskowal
Forked from tlrobinson/makeFunctionSerial.js
Created March 1, 2011 22:19
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 kriskowal/850007 to your computer and use it in GitHub Desktop.
Save kriskowal/850007 to your computer and use it in GitHub Desktop.
var Q = require("q");
var Queue = require("q/queue").Queue;
function throttle(max, wrapped) {
var queue = Queue();
var pending = 0;
function loop() {
return Q.when(queue.get(), function (next) {
var done = Q.defer();
function wrap(callback) {
return function () {
done.resolve(callback.apply(this, arguments));
}
}
wrapped.apply(next["this"], [wrap].concat(next["args"]));
return Q.when(done.promise, function () {
pending--;
return loop();
});
});
}
loop();
return function () {
if (pending <= max) {
pending++;
queue.put({
"this": this,
"args": Array.prototype.slice.call(arguments)
});
}
}
}
// contrived example
var serialSetTimeout = throttle(2, function (wrap, callback, delay) {
return setTimeout(wrap(callback), delay);
});
serialSetTimeout(function() { console.log("a"); }, 2000); // t=2s
serialSetTimeout(function() { console.log("b"); }, 1000); // t=3s
serialSetTimeout(function() { console.log("c"); }, 1000); // t=4s
serialSetTimeout(function() { console.log("d"); }, 1000); // dropped!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment