Created
August 13, 2012 21:02
-
-
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.
This file contains hidden or 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
/* | |
* 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