Skip to content

Instantly share code, notes, and snippets.

@mikehenrty
Last active February 6, 2017 12:31
Show Gist options
  • Save mikehenrty/e2d83aae1e3bd8a3898da0cae739ebaf to your computer and use it in GitHub Desktop.
Save mikehenrty/e2d83aae1e3bd8a3898da0cae739ebaf to your computer and use it in GitHub Desktop.
A simple task queue class
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