Skip to content

Instantly share code, notes, and snippets.

@peterudo
Created August 10, 2012 07:27
Show Gist options
  • Save peterudo/3312276 to your computer and use it in GitHub Desktop.
Save peterudo/3312276 to your computer and use it in GitHub Desktop.
Queue
function job(done) {
console.log('working hard...');
setTimeout(function () {
done();
}, 1000);
}
var queue = new Queue();
queue.add(job, true);
queue.add(job, true);
queue.dispatch();
setTimeout(function () {
queue.add(job);
queue.add(job);
}, 200)
var Queue = function () {
this.running = false;
this.jobs = [];
this._dispatchNextJob = this._dispatchNextJob.bind(this);
};
Queue.prototype.dispatch = function() {
if (this.running) {
return;
}
console.log('dispatch');
this._dispatchNextJob();
};
Queue.prototype._dispatchNextJob = function() {
if (!this.jobs[0]) {
this.running = false;
return;
}
this.running = true;
this.jobs.shift()(this._dispatchNextJob);
};
Queue.prototype.add = function(callback, defer) {
this.jobs.push(callback);
if (!defer) {
this.dispatch();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment