Skip to content

Instantly share code, notes, and snippets.

@jakobmattsson
Created March 18, 2012 15:08
Show Gist options
  • Save jakobmattsson/2075035 to your computer and use it in GitHub Desktop.
Save jakobmattsson/2075035 to your computer and use it in GitHub Desktop.
Function.prototype.queue
var queue = function(f) {
var queue = [];
var running = false;
var initiate = function() {
if (running || queue.length == 0) {
return;
}
running = true;
var head = queue[0];
var callback = head.arguments[head.arguments.length-1];
queue = queue.slice(1);
head.arguments[head.arguments.length-1] = function() {
callback.apply(this, arguments);
running = false;
initiate();
};
f.apply(head.context, head.arguments);
};
return function() {
queue.push({ context: this, arguments: arguments });
initiate();
};
};
Function.prototype.queue = function() {
return queue(this);
};
var f1 = function(x, callback) {
setTimeout(function() {
console.log(x);
callback();
}, Math.random() * 1000);
};
var f2 = function(x, callback) {
console.log(x);
callback();
};
var noop = function() {};
f1 = f1.queue();
f2 = f2.queue();
f1(1, noop);
f1(2, noop);
f1(3, noop);
f1(4, noop);
f1(5, noop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment