From 5d7279ce607d60774671610137487c88b5ef04cd Mon Sep 17 00:00:00 2001 From: Nuruddin Ashr Date: Fri, 16 Mar 2018 09:26:59 +0700 Subject: [PATCH] No longer use timer --- waitgroup.js | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/waitgroup.js b/waitgroup.js index 31790ae..3133ebd 100644 --- a/waitgroup.js +++ b/waitgroup.js @@ -22,24 +22,43 @@ var WaitGroup = function(){ this.total = 0; // Number of total items this.ready = 0; // Number of items ready + this.callbacks = [] // The wait callbacks }; WaitGroup.prototype.add = function WaitGroupAdd(){ this.total++; + if (hasToEmit(this)) { + emitCallbacks(this); + } }; WaitGroup.prototype.done = function WaitGroupDone(){ this.ready++; + if (hasToEmit(this)) { + emitCallbacks(this); + } }; WaitGroup.prototype.wait = function(fn) { - var self = this; - setTimeout(function(){ - if(self.ready == self.total) return fn(); - self.wait(fn); - }, 0); + this.callbacks.push(fn); + if (hasToEmit(this)) { + emitCallbacks(this); + } }; +function hasToEmit(wg) { + return wg.ready === wg.total; +} + +function emitCallbacks(wg) { + var callbacks = wg.callbacks; + for (var i = 0; i < callbacks.length; i++) { + var cb = callbacks[i]; + cb(); + } + wg.callbacks = []; +} + // Export to node.js if(typeof(module) !== "undefined") { module.exports = WaitGroup;