Skip to content

Instantly share code, notes, and snippets.

@oleh-zaporozhets
Created July 25, 2023 17:28
Show Gist options
  • Save oleh-zaporozhets/45b647f119a565bf7f2dbfa6f1c2ae9c to your computer and use it in GitHub Desktop.
Save oleh-zaporozhets/45b647f119a565bf7f2dbfa6f1c2ae9c to your computer and use it in GitHub Desktop.
type Callback = () => Promise<void> | void;
interface ITimer {
reset(): void;
refresh(): void;
isTimerRunning(): boolean;
}
class Timer implements ITimer {
private callbacks: Callback[];
private timer: NodeJS.Timeout | null;
private interval: number;
private isRunning = false;
public constructor(callbacks: Callback[], interval: number) {
this.callbacks = callbacks;
this.interval = interval;
this.timer = setTimeout(this.runTimerCallbacks, this.interval);
}
public reset = (): void => {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(this.runTimerCallbacks, this.interval);
this.isRunning = true;
};
public refresh = (): void => {
if (!this.timer) {
throw new Error('Timer should be initialized first');
}
this.timer.refresh();
};
public isTimerRunning() {
return this.isRunning;
}
private runTimerCallbacks = async (): Promise<void> => {
this.isRunning = false;
for (const callback of this.callbacks) {
await callback();
}
};
}
export { ITimer, Timer };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment