Skip to content

Instantly share code, notes, and snippets.

@kirbysayshi
Created February 15, 2015 04:30
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 kirbysayshi/190b17329defe007d3f1 to your computer and use it in GitHub Desktop.
Save kirbysayshi/190b17329defe007d3f1 to your computer and use it in GitHub Desktop.
A Task Queue, because sometimes I don't want to learn another API
var tasks = new TaskQueue(5);
tasks.queue(getUrl.bind(null, 'google.com'))
tasks.queue(getUrl.bind(null, 'yahoo.com'))
tasks.queue(getUrl.bind(null, 'facebook.com'))
tasks.next() // kick it.
function getUrl(url, cb) {
magicalXHR(url, cb);
}
function TaskQueue(concurrency) {
var _queue = [];
var _concurrents = 0;
var ctr = {
queue: function(fn) {
_queue.push(fn)
},
next: function() {
while (_concurrents < concurrency) {
_concurrents += 1;
var t = _queue.shift();
if (!t) return;
t(function() {
_concurrents -= 1;
ctr.next();
});
}
}
}
return ctr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment