Create a gist now

Instantly share code, notes, and snippets.

CountdownLatch
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;
};
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
@velickym

Respect man - nice, simple and extremely handy. Thanks.

@dhirajforyou

Yes, Simple and excellent work.

@sukima

You could make this API even better with an async function:

var CountdownLatch = function (limit){
  this.limit = limit;
  this.count = 0;
  this.waitBlock = function (){};
};
CountdownLatch.prototype.async = function (fn){
  var _this = this;
  fn(function (){
    _this.count = _this.count + 1;
    if(_this.limit <= _this.count){
      return _this.waitBlock();
    }
  });
};
CountdownLatch.prototype.await = function(callback){
  this.waitBlock = callback;
};
var barrier = new CountdownLatch(2);

barrier.async(function (done){
  setTimeout(function (){
    console.log('work A');
    done();
  }, 100);
});
barrier.async(function (done){
  setTimeout(function (){
    console.log('work B');
    done();
  }, 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

JSBin example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment