Created
July 20, 2017 14:55
-
-
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
This file contains 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
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