I'm seeking code review comments for the following implementation.
/**
* You need to run a number of async tasks, but you're being rate limited.
* Run as many concurrent tasks as you can, queueing the rest for when the
* tasks are complete.
*/
/**
* @param concurrency: number of concurrent tasks that can be run
*/
var ConcurrencyQueue = function (concurrency) {
this.concurrency = concurrency;
this.queue = [];
this.count = 0;
};
/**
* add an asynchronous task to the queue. it will get executed immediately
* until the concurrent task count reaches this.concurrency. then, queue it until
* tasks are complete.
* @param task: function which takes a callback argument (done)
*/
ConcurrencyQueue.prototype.enqueue = function (task) {
var self = this;
self.count = self.count + 1;
var done = function () {
self.count = self.count - 1;
if (self.queue.length) {
self.queue.splice(0, 1)[0](done);
}
};
if (self.count > self.concurrency) {
self.queue.push(task);
}
if (self.count <= self.concurrency) {
task(done);
}
};
/**
* tasks passed to concurrency queue are async and call the callback "done"
* after they complete.
*/
function exampleTask (done) {
console.log('started');
setTimeout(function () {
console.log('completed');
done();
}, Math.floor(Math.random() * 2000));
};
var queue = new ConcurrencyQueue(2);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);