Created
March 9, 2022 15:54
-
-
Save jabez007/d54d211c93517dfa97ffea0dc48cbca1 to your computer and use it in GitHub Desktop.
Expanding on an idea from https://www.matteoagosti.com/blog/2013/01/22/rate-limiting-function-calls-in-javascript/ to return Promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.RateLimit = (function () { | |
var RateLimit = function (maxOps, interval, allowBursts) { | |
this._maxRate = allowBursts ? maxOps : maxOps / interval; | |
this._interval = interval; | |
this._allowBursts = allowBursts; | |
this._numOps = 0; | |
this._start = new Date().getTime(); | |
this._queue = []; | |
}; | |
RateLimit.prototype.schedule = function (fn) { | |
var that = this, | |
rate = 0, | |
now = new Date().getTime(), | |
elapsed = now - this._start; | |
if (elapsed > this._interval) { | |
this._numOps = 0; | |
this._start = now; | |
} | |
rate = this._numOps / (this._allowBursts ? 1 : elapsed); | |
if (rate < this._maxRate) { | |
if (this._queue.length === 0) { | |
this._numOps++; | |
return Promise.resolve(fn()); | |
} else { | |
if (fn) this._queue.push(fn); | |
this._numOps++; | |
return Promise.resolve(this._queue.shift()()); | |
} | |
} else { | |
if (fn) this._queue.push(fn); | |
return new Promise((resolve, reject) => | |
setTimeout(function () { | |
resolve(that.schedule()); | |
}, 1 / this._maxRate) | |
); | |
} | |
}; | |
return RateLimit; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment