Skip to content

Instantly share code, notes, and snippets.

@Ovyerus
Created October 6, 2016 06:31
Show Gist options
  • Save Ovyerus/d74a568a9864366a65fda5461d102891 to your computer and use it in GitHub Desktop.
Save Ovyerus/d74a568a9864366a65fda5461d102891 to your computer and use it in GitHub Desktop.
class Timer {
constructor(func, time) {
if (typeof func !== 'function') throw new Error('func is not a function');
if (typeof time !== 'number') throw new Error('time is not a number');
this.timerObj = setInterval(func, time);
this.func = func;
this.time = time;
}
stop() {
if (this.timerObj) {
clearInterval(this.timerObj);
this.timerObj = null;
}
return this;
}
start() {
if (!this.timerObj) {
this.stop();
this.timerObj = setInterval(this.func, this.time);
}
return this;
}
restart() {
return this.stop().start();
}
changeTime(newTime) {
if (typeof newTime !== 'number') throw new Error('newTime is not a number');
this.time = newTime;
return this.stop().start();
}
changeFunc(newFunc) {
if (typeof newTime !== 'function') throw new Error('newFunc is not a function');
this.func = newFunc;
return this.stop();
}
executeFunc() {
return this.func();
}
}
module.exports = Timer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment