Created
January 1, 2012 18:16
-
-
Save deoxxa/1547961 to your computer and use it in GitHub Desktop.
javascript job queue
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
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