Skip to content

Instantly share code, notes, and snippets.

@sukima
Forked from nowelium/latch.js
Last active September 5, 2016 16:48
Show Gist options
  • Save sukima/ef15ae09bc829f415cad7708f9882df2 to your computer and use it in GitHub Desktop.
Save sukima/ef15ae09bc829f415cad7708f9882df2 to your computer and use it in GitHub Desktop.
CountdownLatch
var CountdownLatch = function (limit) {
this.limit = limit;
this.count = 0;
this.waitBlock = function () {};
};
CountdownLatch.prototype.async = function (fn, ctx) {
var _this = this;
fn.call(ctx, 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment