Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active December 11, 2015 12:08
Show Gist options
  • Save catdad/4598289 to your computer and use it in GitHub Desktop.
Save catdad/4598289 to your computer and use it in GitHub Desktop.
This function can be used to sync many asynchronous functions. You only have to maintain the list and order once, and they will execute one after the other, as well as a callback after all the functions are done.
function firstFunction(next){
console.log('first function');
setTimeout(next, 1000);
}
function secondFunction(next){
console.log('second function');
setTimeout(next, 1000);
}
function sync(funcs, done){
var counter = funcs.length;
var idx = 0;
var next = function() {
if (--counter === 0) done();
else funcs[idx++](next);
};
funcs[idx++](next);
}
function over(){ console.log('async functions are over') };
sync([firstFunction, secondFunction], over);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment