public
Created

CountdownLatch

  • Download Gist
latch.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var CountdownLatch = function (limit){
this.limit = limit;
this.count = 0;
this.waitBlock = function (){};
};
CountdownLatch.prototype.countDown = function (){
this.count = this.count + 1;
if(this.limit <= this.count){
return this.waitBlock();
}
};
CountdownLatch.prototype.await = function(callback){
this.waitBlock = callback;
};
latch_barrier.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
var barrier = new CountdownLatch(2);
 
setTimeout(function (){
console.log('work A');
barrier.countDown();
}, 100);
setTimeout(function (){
console.log('work B');
barrier.countDown();
}, 200);
 
console.log('wait for all to finish...');
barrier.await(function(){
console.log('done all');
});
 
==>
wait for all to finish...
work A
work B
done all

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.