Skip to content

Instantly share code, notes, and snippets.

@tbremer
Last active February 18, 2019 21:36
Show Gist options
  • Save tbremer/18dfbc6d7cc9d86bc1ca7843e835755e to your computer and use it in GitHub Desktop.
Save tbremer/18dfbc6d7cc9d86bc1ca7843e835755e to your computer and use it in GitHub Desktop.
scheduler

scheduler

const schedule = new scheduler(() => console.log("Hello, world!"), 1500);

schedule.setInterval(); // start the logger
schedule.pause(3e3); // pause the logger for 3 seconds
class scheduler {
constructor(callback, timer) {
this.callback = callback;
this.timer = timer;
this.id = null;
this.recurring = null;
}
get isRunning() {
return this.id !== null;
}
get isRecurring() {
return this.recurring === null ? false : this.recurring;
}
setInterval() {
this.id = setInterval(this.callback, this.timer)
this.recurring = true;
}
setTimeout() {
this.id = setTimeout(this.callback, this.timer);
this.recurring = false;
}
pause(timer = Infinity) {
if (this.recurring) {
clearInterval(this.id);
}
else {
clearTimeout(this.id);
}
this.id = null;
if (timer !== Infinity) {
setTimeout(() => {
if (this.recurring) this.setInterval(this.callback, this.timer);
else this.setTimeout(this.callback, this.timer);
}, timer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment