public

  • Download Gist
makeFunctionSerial.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 
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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.