Skip to content

Instantly share code, notes, and snippets.

@mcfedr
Created August 13, 2012 21:02
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 mcfedr/3344088 to your computer and use it in GitHub Desktop.
Save mcfedr/3344088 to your computer and use it in GitHub Desktop.
callback lock queue - simple way to make functions that rely on callbacks execute serially.
/*
* return an object with two functions
* push - push an invocation of t.f(args) which will be called immediately if the q is empty
* next - the function that should be called in f to signal that the next invocation can be run
* important! - every function given to push should call next
*/
function lock() {
var q = [], busy = false;
return {
push: function(f, args, t) {
if(!busy) {
busy = true;
f.apply(t, args);
}
else {
q.push({f: f, args: args, t: t});
}
},
next: function() {
if(q.length > 0) {
var n = q.shift();
n.f.apply(n.t, n.args);
}
else {
busy = false;
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment