Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

removes requestsPerInterval option, adds a callback when all requests…

… are done
  • Loading branch information...
commit 458a800045d1892ef1cfe6bd3c81837db5b15afd 1 parent c557e27
@manuelstofer authored
Showing with 51 additions and 33 deletions.
  1. +51 −33 lib/trickle.js
View
84 lib/trickle.js
@@ -1,41 +1,59 @@
var VERSION = '0.0.1';
-var Trickle = function (requestsPerInterval, interval) {
- this.requestsPerInterval = requestsPerInterval;
- this.interval = interval;
- this.availableRequests = requestsPerInterval;
-
- this.lastReload = new Date();
+var Trickle = function (interval, callback) {
+ this._interval = interval;
+ this._requests = [];
+ this._lastRun = 0;
+ this._callback = callback;
};
-Trickle.prototype.trickle = function (requests, callback) {
- if (requests > this.requestsPerInterval) {
- var error = { 'code' : 42, 'message' : 'It\'s not gonna happen, ever.' };
- callback(error);
- return;
- }
-
- var self = this;
- this.reload();
-
- if (requests > this.availableRequests) {
- var wait = Math.ceil((requests - this.availableRequests) * (this.interval / this.requestsPerInterval));
- setTimeout(function() { self.trickle(requests, callback); }, wait);
- return false;
+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();
}
-
- this.availableRequests -= requests;
- callback(null);
};
-Trickle.prototype.reload = function () {
- var now = new Date();
- var delta = Math.min(now - this.lastReload, this.interval);
- this.lastReload = now;
-
- var reload = delta * (this.requestsPerInterval / this.interval);
- this.availableRequests = Math.min(this.availableRequests + reload, this.requestsPerInterval);
+module.exports = {
+ VERSION: VERSION,
+ Trickle: Trickle
};
-
-exports.VERSION = VERSION;
-exports.Trickle = Trickle;
Please sign in to comment.
Something went wrong with that request. Please try again.