Created
December 14, 2021 19:11
-
-
Save dav-m85/9640223bd78703af1a55190df371c56d to your computer and use it in GitHub Desktop.
A ticker class encapsulating setInterval
This file contains 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
/** | |
* 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