Skip to content

Instantly share code, notes, and snippets.

@bobrik
Created May 14, 2013 13:37
Show Gist options
  • Save bobrik/5575923 to your computer and use it in GitHub Desktop.
Save bobrik/5575923 to your computer and use it in GitHub Desktop.
does anyone know an npm module for this?
(function() {
var func, started;
function sync(fn) {
var running = false,
requested = [];
return function me(callback) {
if (running) {
requested.push(callback);
return;
}
running = true;
fn(function() {
callback.apply(this, arguments);
running = false;
if (requested.length) {
me(requested.shift());
}
});
}
}
func = sync(function(callback) {
setTimeout(callback, 1000);
});
started = Date.now();
func(function() {
console.log("after a while me #1", Date.now() - started);
});
func(function() {
console.log("after a while me #2", Date.now() - started);
});
func(function() {
console.log("after a while me #3", Date.now() - started);
});
})();
@bobrik
Copy link
Author

bobrik commented May 14, 2013

Output:

after a while me #1 1019
after a while me #2 2038
after a while me #3 3039

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment