Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.