42 lines
851 B
JavaScript
42 lines
851 B
JavaScript
// retoor <retoor@molodetz.nl>
|
|||
|
|
export class Poller {
|
||
|
|
constructor(fn, intervalMs, { immediate = false, pauseHidden = true } = {}) {
|
||
|
|
this.fn = fn;
|
||
|
|
this.intervalMs = intervalMs;
|
||
|
|
this.immediate = immediate;
|
||
|
|
this.pauseHidden = pauseHidden;
|
||
|
|
this.timer = null;
|
||
|
|
this.busy = false;
|
||
|
|
}
|
||
|
|
|
||
|
|
start() {
|
||
|
|
if (this.timer) {
|
||
|
|
return this;
|
||
|
|
}
|
||
|
|
if (this.immediate) {
|
||
|
|
this.tick();
|
||
|
|
}
|
||
|
|
this.timer = setInterval(() => this.tick(), this.intervalMs);
|
||
|
|
return this;
|
||
|
|
}
|
||
|
|
|
||
|
|
stop() {
|
||
|
|
clearInterval(this.timer);
|
||
|
|
this.timer = null;
|
||
|
|
}
|
||
|
|
|
||
|
|
async tick() {
|
||
|
|
if (this.busy || (this.pauseHidden && document.hidden)) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
this.busy = true;
|
||
|
|
try {
|
||
|
|
await this.fn();
|
||
|
|
} catch (error) {
|
||
|
|
console.debug("poller tick failed", error);
|
||
|
|
} finally {
|
||
|
|
this.busy = false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|