diff --git a/lib/tqueue.js b/lib/tqueue.js index 32e753b..020edce 100644 --- a/lib/tqueue.js +++ b/lib/tqueue.js @@ -24,22 +24,26 @@ util.inherits(TQueue, EventEmitter); TQueue.prototype.push = function(item) { var self = this; + if (self.empty()) { + setTimeout(self.curry(self), this.delay); + this.emit('start'); + } + this._items.push(item); this.emit('push', item); - if(this._intervalId == 0) { - this._intervalId = setInterval(function(){self.pop()}, this.delay); - this.emit('start'); - } }; -TQueue.prototype.pop = function() { - if(!this.empty()) { - this.emit('pop', (this.fifo ? this._items.shift() : this._items.pop())); +TQueue.prototype.curry = function(obj) { + return function() { obj.pop(obj) } +}; + +TQueue.prototype.pop = function(self) { + if(!self.empty()) { + self.emit('pop', (self.fifo ? self._items.shift() : self._items.pop())); + setTimeout(self.curry(self), self.delay); } else { - clearInterval(this._intervalId); - this._intervalId = 0; - this.emit('empty'); + self.emit('empty'); } }; @@ -51,4 +55,8 @@ TQueue.prototype.empty = function() { return (this.length() == 0); }; +TQueue.prototype.setDelay = function(delay) { + this.delay = delay; +} + module.exports = TQueue; \ No newline at end of file diff --git a/test/tqueue.js b/test/tqueue.js index 6ad038f..f1b4d45 100644 --- a/test/tqueue.js +++ b/test/tqueue.js @@ -71,4 +71,52 @@ describe('tqueue', function() { } }); }); + + describe('#variable delay', function() { + it('should return variable delay in increments of ~1000', function(done) { + this.timeout(10000); + + var q = new TQueue(); + var i = 0; + var d = 0; + + q.push(1); + q.push(2); + q.push(3); + q.push(4); + + q.on('pop', function() { + switch(i) { + case 0: + d = Date.now(); + q.delay.should.equal(1000); + break; + case 1: + e = Date.now() - d; + d = Date.now(); + e.should.be.within(995, 1005); + q.delay.should.equal(1000); + q.setDelay(2000); + break; + case 2: + e = Date.now() - d; + d = Date.now(); + e.should.be.within(1995, 2005); + q.delay.should.equal(2000); + q.setDelay(3000); + break; + case 3: + e = Date.now() - d; + e.should.be.within(2995, 3005); + q.delay.should.equal(3000); + done(); + break; + } + i++; + }); + }); + }); + + + }); \ No newline at end of file