Skip to content

Instantly share code, notes, and snippets.

@garbados
Last active December 20, 2015 04:39
Show Gist options
  • Save garbados/6072792 to your computer and use it in GitHub Desktop.
Save garbados/6072792 to your computer and use it in GitHub Desktop.
JavaScript "Counter" object for iterating over asynchronous tasks, so you can do something once they're done even if they don't complete in any known order.
// calls `cb` after `next()` meets `end`
// useful for asynchronous iteration
var Counter = function(end, cb){
this._count = 0;
this.next = function(){
this._count++;
if(this._count === end){
cb();
}
}
}
var counter = Counter(queue.length, function(){
// runs when counter has been called as many times as there are items in queue
console.log('Finished!');
});
queue.forEach(function(item){
asynchronous_stuff(function(results){
// handle results
counter.next();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment