Skip to content

Instantly share code, notes, and snippets.

@btford
Created June 19, 2013 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btford/5818729 to your computer and use it in GitHub Desktop.
Save btford/5818729 to your computer and use it in GitHub Desktop.
var mutexify = function (fn, lim) {
var queue = [];
var inProgress = 0;
var invokeNext = function () {
if (queue.length === 0) {
return;
}
if (inProgress >= lim) {
return;
}
inProgress += 1;
var next = queue.shift();
fn(next.arg, function () {
next.cb.apply(fn, arguments);
inProgress -= 1;
setTimeout(invokeNext, 0);
});
};
return function (arg, cb) {
queue.push({
arg: arg,
cb: cb
});
setTimeout(invokeNext, 0);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment