@smoovy/ticker
Version:
Simple and easy-to-use ticker
69 lines (68 loc) • 1.6 kB
JavaScript
"use strict";
const _Ticker = class {
constructor(override = false) {
this.override = override;
this.ticking = false;
this.offset = 0;
this.tasks = [];
this.time = 0;
this.pauseStart = -1;
if (!this.override) {
if (document && document instanceof Document) {
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
this.pauseStart = performance.now();
} else if (this.pauseStart >= -1) {
this.offset += performance.now() - this.pauseStart;
this.pauseStart = -1;
}
});
}
this.loop();
}
}
static now() {
return this.main.time;
}
tick(passed) {
let deadTask;
for (const task of this.tasks) {
if (task.dead) {
deadTask = task;
continue;
}
task.update(passed - this.time, this.time - task.start, task.kill);
}
if (deadTask) {
this.tasks.splice(this.tasks.indexOf(deadTask), 1);
}
this.time = passed;
}
loop() {
this.ticking = true;
window.requestAnimationFrame((time) => {
this.tick(time - this.offset);
if (!this.override) {
this.loop();
} else {
this.ticking = false;
}
});
}
add(update, order = 0) {
const task = {
update,
order,
start: this.time,
dead: false,
kill: () => {
task.dead = true;
}
};
this.tasks.push(task);
this.tasks.sort((a, b) => a.order - b.order);
return task;
}
};
export let Ticker = _Ticker;
Ticker.main = new _Ticker();