Skip to content

Instantly share code, notes, and snippets.

@a1xon
Created March 17, 2022 15:47
Show Gist options
  • Save a1xon/a05f6822840a4e74c4777ca6f7f77387 to your computer and use it in GitHub Desktop.
Save a1xon/a05f6822840a4e74c4777ca6f7f77387 to your computer and use it in GitHub Desktop.
Pausable Interval in ES6
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