UNPKG

@splitsoftware/splitio-commons

Version:
62 lines (61 loc) 2.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Backoff = void 0; var Backoff = /** @class */ (function () { /** * Schedule function calls with exponential backoff */ function Backoff(cb, baseMillis, maxMillis) { this.baseMillis = Backoff.__TEST__BASE_MILLIS || baseMillis || Backoff.DEFAULT_BASE_MILLIS; this.maxMillis = Backoff.__TEST__MAX_MILLIS || maxMillis || Backoff.DEFAULT_MAX_MILLIS; this.attempts = 0; this.cb = cb; } /** * Schedule a next call to `cb` * @returns scheduled delay in milliseconds */ Backoff.prototype.scheduleCall = function () { var _this = this; var delayInMillis = Math.min(this.baseMillis * Math.pow(2, this.attempts), this.maxMillis); if (this.timeoutID) clearTimeout(this.timeoutID); this.timeoutID = setTimeout(function () { _this.timeoutID = undefined; _this.cb(); }, delayInMillis); this.attempts++; return delayInMillis; }; /** * Schedule a delayed call to `cb` * @returns a promise that resolves/rejects with the result of the `cb` function, which must return a promise. */ Backoff.prototype.scheduleCallAsync = function () { var _this = this; var delayInMillis = Math.min(this.baseMillis * Math.pow(2, this.attempts), this.maxMillis); if (this.timeoutID) clearTimeout(this.timeoutID); this.attempts++; return new Promise(function (resolve, reject) { _this.timeoutID = setTimeout(function () { _this.timeoutID = undefined; _this.cb().then(resolve, reject); }, delayInMillis); }); }; /** * Reset the backoff attempts */ Backoff.prototype.reset = function () { this.attempts = 0; if (this.timeoutID) { clearTimeout(this.timeoutID); this.timeoutID = undefined; } }; Backoff.DEFAULT_BASE_MILLIS = 1000; // 1 second Backoff.DEFAULT_MAX_MILLIS = 1800000; // 30 minutes return Backoff; }()); exports.Backoff = Backoff;