Skip to content

Instantly share code, notes, and snippets.

@liorama
Created July 20, 2017 14:55
Show Gist options
  • Save liorama/2707929b84703b61a228a86bc67fda11 to your computer and use it in GitHub Desktop.
Save liorama/2707929b84703b61a228a86bc67fda11 to your computer and use it in GitHub Desktop.
WrapCb will wrap all callbacks counting them and calling finalCb when all CB's were called
var cbCounter = 0
function finalCb(){
// Do something when all CBs are called
}
function wrapCb(cb, context){
cbCounter++;
return function(){ // context is optional, if you need to have the `this` changed for the CB
cb && cb.call(context || this); // so CB isn't mandatory
cbCounter--;
if(cbCounter === 0){
finalCb();
}
}
}
/* test */
finalCb = console.log.bind(console, 'final cb'); // Overwriting the prototype from above
for(var i = 0; i < 5000; i++){
setTimeout(wrapCb(console.log.bind(console, i)), 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment