I've written a simple multithreaded queue manager in JavaScript which will be seeing some pretty heavy usage at a later point in the project I'm working on. I think it's pretty solid, but I wouldn't mind hearing some other opinions on it. Any potential problems?
For convenience, here's a JSBin example of the queue.
function Queue(callback, threads, queue) {
var q = this;
// variables
this.queue = queue || [];
this.callback = callback;
this.threads = threads || 1;
// add element to the queue to be checked
this.add = function (elem) {
this.queue.push(elem);
};
// this should be called when the execute function has finished
this.continue = function (delay) {
if (!delay) {
// if there's no delay, just call the function immediately
if (!this.queue.length) {
return;
}
this.callback.call(this, this.queue.shift());
} else {
// otherwise, wait until later to call the function
setTimeout(function () {
// anything left in the queue?
if (!q.queue.length) {
return;
}
q.callback.call(q, q.queue.shift());
}, delay);
}
};
// begin iterating through the queue
this.begin = function () {
var i = this.threads;
while (i--) {
this.continue();
}
};
}
Example usage:
// create object
var q = new Queue();
// specify maximum threads
q.threads = 10;
// and a callback
q.callback = function (item) {
// do stuff with item
console.log(item);
// only call this when this function has finished
// number is the delay in ms to wait before continuing
this.continue(1000);
};
// add some items to the queue
for (var i = 0; i < 100; i++) {
q.add(i);
}
// begin working through the queue
q.begin();
setTimeout
reasonably enough to warrant the title of this question. – Elliot Bonneville Oct 15 '14 at 22:37