assassin-bug/framework/scheduler/timer.js

40 lines
1.0 KiB
JavaScript
Raw Permalink Normal View History

2022-11-26 01:22:02 +00:00
export class Timer {
constructor(time, node) {
this.time = time;
this.node = node;
this.isStarted = false;
}
start() {
this.isStarted = true;
this.schedule();
}
stop() {
if (this.isStarted) {
if (this.intervalID) {
clearTimeout(this.intervalID);
this.intervalID = null;
this.isStarted = false;
}
}
}
schedule() {
let toWait = this.time;
if (this.lastTime) {
const fluc = Date.now() - this.lastTime;
this.fluctuation = fluc;
toWait -= fluc;
}
this.lastTime = Date.now();
this.intervalID = setTimeout(this.handleResolve.bind(this), toWait);
}
handleResolve() {
this.lastTime = Date.now();
if (this.node) {
this.node.func(this.time / this.lastTime);
}
if (this.isStarted) {
this.schedule();
}
}
}