Skip to content

Instantly share code, notes, and snippets.

@pluveto
Created December 10, 2023 07:12
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 pluveto/3b07df4b0db077469c86ea59679aacc5 to your computer and use it in GitHub Desktop.
Save pluveto/3b07df4b0db077469c86ea59679aacc5 to your computer and use it in GitHub Desktop.
Typescript controllable Timer implementation
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