|
// retoor <retoor@molodetz.nl>
|
|
|
|
export class Poller {
|
|
constructor(fn, intervalMs, options = {}) {
|
|
this._fn = fn;
|
|
this._interval = intervalMs;
|
|
this._pauseHidden = !!options.pauseHidden;
|
|
this._timer = null;
|
|
this._busy = false;
|
|
if (options.immediate !== false) this.tick();
|
|
this.start();
|
|
}
|
|
|
|
start() {
|
|
if (this._timer) return;
|
|
this._timer = window.setInterval(() => this.tick(), this._interval);
|
|
}
|
|
|
|
stop() {
|
|
if (this._timer) {
|
|
window.clearInterval(this._timer);
|
|
this._timer = null;
|
|
}
|
|
}
|
|
|
|
async tick() {
|
|
if (this._pauseHidden && document.hidden) return;
|
|
if (this._busy) return;
|
|
this._busy = true;
|
|
try {
|
|
await this._fn();
|
|
} catch (error) {
|
|
return;
|
|
} finally {
|
|
this._busy = false;
|
|
}
|
|
}
|
|
}
|