From 27b990edbae4c2926bbbd6923bf5fe4d34f50e2c Mon Sep 17 00:00:00 2001 From: Manuel Stofer Date: Tue, 14 Feb 2012 00:02:39 +0100 Subject: [PATCH] adds browser compatibility, avoid global namespace pollution in browsers - add trickle to window namespace if module is not defined - this should make trickle usable in browsers --- lib/trickle.js | 126 ++++++++++++++++++++++++++----------------------- 1 file changed, 67 insertions(+), 59 deletions(-) diff --git a/lib/trickle.js b/lib/trickle.js index 564e178..9c665b3 100644 --- a/lib/trickle.js +++ b/lib/trickle.js @@ -1,59 +1,67 @@ -var VERSION = '0.0.1'; - -var Trickle = function (interval, callback) { - this._interval = interval; - this._requests = []; - this._lastRun = 0; - this._callback = callback; -}; - -Trickle.prototype = { - - trickle: function (callback) { - var self = this; - this._requests.push(callback); - process.nextTick(function () { self._run(); }); - }, - - isEmpty: function () { - return this._requests.length === 0; - }, - - _run: function () { - var now = (new Date()).getTime(); - - if (this._isReady()) { - this._requests.shift().call(); - this._lastRun = now; - - if (!this.isEmpty()) { - this._plan(); - } - - } else if (!this._planed) { - this._plan(this._lastRun + this._interval - now); - } - - if (this.isEmpty() && this._callback) { - this._callback(); - } - }, - - _plan: function (to) { - var self = this; - self._planed = true; - setTimeout(function () { - self._planed = false; self._run(); - }, to || this._interval - ); - }, - - _isReady: function () { - return this._lastRun === null || this._lastRun + this._interval <= (new Date()).getTime(); - } -}; - -module.exports = { - VERSION: VERSION, - Trickle: Trickle -}; +;(function () { + + var VERSION = '0.0.1'; + + var Trickle = function (interval, callback) { + this._interval = interval; + this._requests = []; + this._lastRun = 0; + this._callback = callback; + }; + + Trickle.prototype = { + + trickle: function (callback) { + var self = this; + this._requests.push(callback); + process.nextTick(function () { self._run(); }); + }, + + isEmpty: function () { + return this._requests.length === 0; + }, + + _run: function () { + var now = (new Date()).getTime(); + + if (this._isReady()) { + this._requests.shift().call(); + this._lastRun = now; + + if (!this.isEmpty()) { + this._plan(); + } + + } else if (!this._planed) { + this._plan(this._lastRun + this._interval - now); + } + + if (this.isEmpty() && this._callback) { + this._callback(); + } + }, + + _plan: function (to) { + var self = this; + self._planed = true; + setTimeout(function () { + self._planed = false; self._run(); + }, to || this._interval + ); + }, + + _isReady: function () { + return this._lastRun === null || this._lastRun + this._interval <= (new Date()).getTime(); + } + }; + + if (typeof module != 'undefined') { + module.exports = { + VERSION: VERSION, + Trickle: Trickle + }; + } else { + window.Trickle = Trickle; + } + +}).call(this);