Skip to content

Instantly share code, notes, and snippets.

@Davenchy
Last active April 11, 2019 16:18
Show Gist options
  • Save Davenchy/0283c9a05a27be111ed50769b0146ddc to your computer and use it in GitHub Desktop.
Save Davenchy/0283c9a05a27be111ed50769b0146ddc to your computer and use it in GitHub Desktop.
Simple timer class
class Timer {
constructor () {
this.timerId = null;
this.isPlaying = false;
this.onTick;
this.onPlay;
this.onStop;
this.onReset;
this.onSetTick;
this.onRemoveTick;
this.ticks = 0;
this.timers = [];
this.tickDuration = 1000;
this.ticksLimit = 50;
this.__tickTimerId__ = 0;
}
__call__(name, ...args) {
if (this[name]) this[name].apply(this, args);
}
setTick(ticks, cb, once = true) {
if (!ticks || !cb) return;
const tick = { id: this.__tickTimerId__, ticks, cb, once };
this.timers.push(tick);
this.__call__('onSetTick', tick);
return this.__tickTimerId__++;
}
removeTick(id) {
const index = this.timers.findIndex(timer => timer.id === id);
if (index !== -1) {
this.__call__('onRemoveTick', this.timers[index]);
this.timers.splice(index, 1);
}
}
play() {
if (this.timerId) this.stop();
this.__call__('onPlay');
this.isPlaying = true;
this.timerId = setInterval((self) => {
// count
if (!self.isPlaying) self.stop();
self.ticks++;
self.__call__('onTick', self.ticks);
// call all callbacks of timers
self.timers
.filter(timer => {
if (timer.once) return self.ticks === timer.ticks;
else self.ticks >= timer.ticks;
})
.forEach(timer => timer.cb(self));
// stop timer after ticks limit
if (self.ticks >= self.ticksLimit && self.ticksLimit !== 0)
self.reset();
}, this.tickDuration, this);
}
reset() {
this.stop();
this.ticks = 0;
this.__call__('onReset');
}
stop() {
if (!this.timerId) return;
clearInterval(this.timerId);
this.timerId = null;
this.isPlaying = false;
this.__call__('onStop');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment