Skip to content

Commit

Permalink
adds browser compatibility, avoid global namespace pollution in browsers
Browse files Browse the repository at this point in the history
- add trickle to window namespace if module is not defined
- this should make trickle usable in browsers
  • Loading branch information
manuelstofer committed Feb 13, 2012
1 parent 45b3a0b commit 27b990e
Showing 1 changed file with 67 additions and 59 deletions.
126 changes: 67 additions & 59 deletions 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);

0 comments on commit 27b990e

Please sign in to comment.