Created
March 17, 2022 15:47
-
-
Save a1xon/a05f6822840a4e74c4777ca6f7f77387 to your computer and use it in GitHub Desktop.
Pausable Interval in ES6
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
class pausableInterval { | |
constructor(callback, intervalMS, instantStart = true) { | |
this.callback = callback; | |
this.intervalMS = intervalMS; | |
this.lastInterval = -Infinity; | |
this.remainingMS = 0; | |
this.paused = false; | |
this.intervalId = null; | |
if (instantStart) { | |
start(); | |
} | |
} | |
pause() { | |
if (!this.paused) { | |
this.clear(); | |
this.remainingMS = new Date().getTime() - this.lastInterval; | |
this.paused = true; | |
} | |
} | |
resume() { | |
if (this.paused) { | |
if (this.remainingMS > 0) { | |
setTimeout(() => { | |
this.run(); | |
this.paused = false; | |
this.start(); | |
}, this.remainingMS); | |
} else { | |
this.paused = false; | |
this.start(); | |
} | |
} | |
} | |
clear() { | |
clearInterval(this.intervalId); | |
} | |
start() { | |
this.clear(); | |
this.intervalId = setInterval(() => { | |
this.run(); | |
}, intervalMS); | |
} | |
run() { | |
this.lastInterval = new Date().getTime(); | |
this.callback(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment