Skip to content

Instantly share code, notes, and snippets.

@dav-m85
Created December 14, 2021 19:11
Show Gist options
  • Save dav-m85/9640223bd78703af1a55190df371c56d to your computer and use it in GitHub Desktop.
Save dav-m85/9640223bd78703af1a55190df371c56d to your computer and use it in GitHub Desktop.
A ticker class encapsulating setInterval
/**
* Usage:
* new Ticker(timeout: number, (stop: Function) => {
* // do stuff every timeout
* if (...) {stop()}
* })
*/
class Ticker {
private ticker: any
private handler: Function
private timeout: number
constructor(timeout: number, handler: Function) {
this.ticker = null
this.handler = handler
this.timeout = timeout
}
handle() {
this.handler(this.stop.bind(this))
}
start() {
if (!this.ticker) {
log("ticker start")
setTimeout(() => this.handle(), 1000) // first exec after 1sec
this.ticker = setInterval(() => this.handle(), this.timeout)
}
}
stop() {
if (this.ticker) {
log("ticker stop")
clearInterval(this.ticker)
this.ticker = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment