Files
discord.js/lib/Util/Bucket.js
2016-08-05 08:11:45 +09:00

56 lines
1.6 KiB
JavaScript

"use strict";
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Bucket = (function () {
// Adapted from Eris
function Bucket(tokenLimit, interval) {
_classCallCheck(this, Bucket);
this.tokenLimit = tokenLimit;
this.interval = interval;
this.extraTime = 500;
this.lastReset = this.tokens = this.lastSend = 0;
this._queue = [];
}
Bucket.prototype.queue = function queue(func) {
this._queue.push(func);
this.check();
};
Bucket.prototype.check = function check() {
var _this = this;
if (this.timeout || this._queue.length === 0) {
return;
}
if (this.lastReset + this.interval + this.extraTime < Date.now()) {
this.lastReset = Date.now();
this.tokens = Math.max(0, this.tokens - this.tokenLimit);
}
var val;
while (this._queue.length > 0 && this.tokens < this.tokenLimit) {
this.tokens++;
this._queue.shift()();
this.lastSend = Date.now();
}
if (this._queue.length > 0 && !this.timeout) {
this.timeout = setTimeout(function () {
_this.timeout = null;
_this.check();
}, this.tokens < this.tokenLimit ? 1 : Math.max(0, this.lastReset + this.interval + this.extraTime - Date.now()));
}
};
return Bucket;
})();
exports["default"] = Bucket;
module.exports = exports["default"];