Skip to content

Instantly share code, notes, and snippets.

@madclaws
Created August 18, 2020 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madclaws/2dc16653b6a1b2a04f6808d77cdb013e to your computer and use it in GitHub Desktop.
Save madclaws/2dc16653b6a1b2a04f6808d77cdb013e to your computer and use it in GitHub Desktop.
A class implementing backoff timer
/*
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