Skip to content

Instantly share code, notes, and snippets.

@jabez007
Created March 9, 2022 15:54
Show Gist options
  • Save jabez007/d54d211c93517dfa97ffea0dc48cbca1 to your computer and use it in GitHub Desktop.
Save jabez007/d54d211c93517dfa97ffea0dc48cbca1 to your computer and use it in GitHub Desktop.
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