-
-
Save kriskowal/850007 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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