Created
December 10, 2023 07:12
-
-
Save pluveto/3b07df4b0db077469c86ea59679aacc5 to your computer and use it in GitHub Desktop.
Typescript controllable Timer implementation
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
import { Logger } from './logger' | |
export class Timer { | |
running?: NodeJS.Timeout | |
timeout: number | |
callback: () => void | |
logger?: Logger | |
constructor(timeout: number, callback: () => void, logger?: Logger) { | |
this.timeout = timeout | |
this.callback = callback | |
this.logger = logger | |
} | |
start() { | |
if (this.running) { | |
this.logger?.error('timer already running but start is called') | |
return | |
} | |
this.running = setTimeout(this.callback, this.timeout) | |
this.logger?.debug('timer started') | |
} | |
cancel() { | |
if (!this.running) { | |
this.logger?.error('timer not running but cancel is called') | |
return | |
} | |
clearTimeout(this.running) | |
this.running = undefined | |
this.logger?.debug('timer cancelled') | |
} | |
reset() { | |
this.cancel() | |
this.start() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment