Created
July 25, 2023 17:28
-
-
Save oleh-zaporozhets/45b647f119a565bf7f2dbfa6f1c2ae9c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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