Created
August 18, 2020 13:36
-
-
Save madclaws/2dc16653b6a1b2a04f6808d77cdb013e to your computer and use it in GitHub Desktop.
A class implementing backoff timer
This file contains 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
/* | |
A Timer to deal with exponential backoff problems | |
(inspired from phoenixjs library , much 💓) | |
*/ | |
export class BackoffTimer { | |
private timer: any; // setTimeout Id. | |
private callbackFunction: typeof Function; | |
private currentTries: number = 0; | |
private maxTries: number = 0; | |
private calculateIntervalFunction = function(tries: number) { | |
const interval = [3000, 5000, 10000][tries] || 15000; | |
console.log("backing off with", interval); | |
return interval; | |
}; | |
public constructor(callback: typeof Function, maxTries: number = 5) { | |
this.callbackFunction = callback; | |
this.maxTries = maxTries; | |
} | |
public getCurrentTries(): number { | |
return this.currentTries; | |
} | |
public reset() { | |
this.currentTries = 0; | |
clearTimeout(this.timer); | |
} | |
public setTimeout() { | |
console.warn("Called setTimeout"); | |
clearTimeout(this.timer); | |
this.timer = setTimeout(() => { | |
++ this.currentTries; | |
this.callbackFunction(); | |
}, this.calculateIntervalFunction(this.currentTries)) | |
} | |
public addCustomTimerIntervalFunction(intervalCalculateFunction: any) { | |
this.calculateIntervalFunction = intervalCalculateFunction; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment