47 lines
995 B
TypeScript
47 lines
995 B
TypeScript
import type { ReactiveController, ReactiveControllerHost } from "lit";
|
|
|
|
type Pulse = () => void;
|
|
|
|
export class PulseController implements ReactiveController {
|
|
host: ReactiveControllerHost;
|
|
|
|
interval: number = 0;
|
|
|
|
timer: number = 0;
|
|
|
|
// eslint-disable-next-line
|
|
_onPulse: Pulse = () => undefined;
|
|
|
|
constructor(host: ReactiveControllerHost, interval: number = 1000, pulse?: Pulse) {
|
|
this.host = host;
|
|
this.host.addController(this);
|
|
if (pulse) {
|
|
this._onPulse = pulse;
|
|
}
|
|
this.handle = this.handle.bind(this);
|
|
this.interval = interval;
|
|
}
|
|
|
|
hostConnected() {
|
|
this.timer = window.setTimeout(this.handle, this.interval);
|
|
}
|
|
|
|
hostDisconnected() {
|
|
if (this.timer !== 0) {
|
|
window.clearTimout(this.timer);
|
|
}
|
|
this.timer = 0;
|
|
}
|
|
|
|
set onPulse(cb: Pulse) {
|
|
this._onPulse = cb;
|
|
}
|
|
|
|
handle() {
|
|
this._onPulse.call(this.host);
|
|
this.timer = window.setTimeout(this.handle, this.interval);
|
|
}
|
|
}
|
|
|
|
export default PulseController;
|