Skip to content

Instantly share code, notes, and snippets.

@deoxxa
Created January 1, 2012 18:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deoxxa/1547961 to your computer and use it in GitHub Desktop.
Save deoxxa/1547961 to your computer and use it in GitHub Desktop.
javascript job queue
module.exports = Queue;
function Queue(action, concurrency) {
this.action = action;
this.concurrency = concurrency || 1;
this.waiting = [];
this.running = 0;
}
Queue.prototype.push = function(data, cb) {
this.waiting.push({data: data, cb: cb});
this.run();
return this;
};
Queue.prototype.run = function() {
for (var i=this.running;i<this.concurrency;++i) {
var job = this.waiting.shift();
if (!job) { break; }
this.running++;
this.action(job.data, this.wrap(job.data, job.cb));
}
return this;
};
Queue.prototype.wrap = function(job, cb) {
var self = this;
return function() {
self.running--;
self.run();
cb.apply(job.data, arguments);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment