Created
August 10, 2012 07:27
-
-
Save peterudo/3312276 to your computer and use it in GitHub Desktop.
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
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) |
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
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