Last active
February 6, 2017 12:31
-
-
Save mikehenrty/e2d83aae1e3bd8a3898da0cae739ebaf to your computer and use it in GitHub Desktop.
A simple task queue class
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 Queue() { | |
this.tasks = []; | |
this.results = []; | |
this.onFinished = null; | |
} | |
Queue.prototype._taskComplete = function() { | |
this.results.push(arguments); | |
this._runNextTask(); | |
}; | |
Queue.prototype._runNextTask = function() { | |
if (this.tasks.length === 0) { | |
// No more tasks, call the callback. | |
this.onFinished(this.results); | |
return; | |
} | |
var task = this.tasks.shift(); | |
task(this._taskComplete.bind(this)); | |
}; | |
Queue.prototype.add = function(task) { | |
this.tasks.push(task); | |
}; | |
Queue.prototype.run = function(cb) { | |
this.onFinished = cb; | |
this.results = []; | |
this._runNextTask(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment