[Backoff] Rewrite to clean up a lot

This commit is contained in:
Ducko 2022-02-12 11:17:04 +00:00
parent c707c7bab4
commit d807128800

View file

@ -1,34 +1,18 @@
module.exports = class Backoff { // Internal library / utility for a class to retry a callback with delays, etc.
constructor(min = 500, max = null) {
this._timeoutId = null; // Setup internal vars
this.fails = 0;
this.min = min; // Setup args
this.max = max ?? (min * 10);
this.current = min;
}
get pending() { // If timeout currently set / waiting
return this._timeoutId !== null;
}
succeed() { // Reset state on succeed
this.current = this.min;
this.fails = 0;
this.cancel();
constructor(min = 500, max = (min * 10)) {
Object.assign(this, { min, max });
this.reset();
this.pending = () => this._timeoutId != null; // If timeout currently set / waiting
}
fail(callback) { // On fail, wait and callback
const delay = this.current * 2;
this.current = Math.min(this.current + (this.current * 2), this.max);
this.current = Math.min(this.current + delay, this.max);
this.fails += 1; // Bump fails
this.fails++; // Bump fails
if (!callback) return this.current; // No callback given, skip rest of this
if (this._timeoutId !== null) throw new Error('Callback already pending call'); // Timeout already set as waiting for another callback to call, throw error
if (this._timeoutId != null) throw new Error(); // Timeout already set as waiting for another callback to call, throw error
this._timeoutId = setTimeout(() => { // Set new timeout
try {
@ -41,10 +25,17 @@ module.exports = class Backoff { // Internal library / utility for a class to re
return this.current;
}
cancel() { // Cancel current timeout
if (this._timeoutId === null) return; // If no timeout already, do nothing
succeed() { // Reset and cancel
this.reset();
this.cancel();
}
clearTimeout(this._timeoutId); // Stop timeout
this_timeoutId = null; // Stop tracking timeout internally as it's been executed
cancel() { // Cancel current timeout
this._timeoutId = clearTimeout(this._timeoutId); // Stop timeout
}
reset() { // Reset internal state
this.current = this.min;
this.fails = 0;
}
};