const schedule = new scheduler(() => console.log("Hello, world!"), 1500);
schedule.setInterval(); // start the logger
schedule.pause(3e3); // pause the logger for 3 seconds
Last active
February 18, 2019 21:36
-
-
Save tbremer/18dfbc6d7cc9d86bc1ca7843e835755e to your computer and use it in GitHub Desktop.
scheduler
This file contains hidden or 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 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