Refactor timers into a simple tested object.

This commit is contained in:
Dermot Duffy
2023-05-20 10:20:39 -07:00
parent 0f7b3cf99e
commit a33d95f491
9 changed files with 154 additions and 105 deletions
+6 -7
View File
@@ -1,4 +1,5 @@
import { FrigateCardMediaPlayer } from '../types';
import { Timer } from './timer';
// The number of seconds to hide the video controls for after loading (in order
// to give a cleaner UI appearance, see:
@@ -15,19 +16,17 @@ const MEDIA_SEEK_CONTROLS_HIDE_SECONDS = 1;
export const hideMediaControlsTemporarily = (
element: HTMLElement & {
controls: boolean;
_controlsHideTimeoutID?: number;
_controlsHideTimer?: Timer;
},
seconds = MEDIA_SEEK_CONTROLS_HIDE_SECONDS,
): void => {
element.controls = false;
if (element._controlsHideTimeoutID) {
window.clearTimeout(element._controlsHideTimeoutID);
}
element._controlsHideTimeoutID = window.setTimeout(() => {
element._controlsHideTimer ??= new Timer();
element._controlsHideTimer.start(seconds, () => {
element.controls = true;
delete element._controlsHideTimeoutID;
}, seconds * 1000);
delete element._controlsHideTimer;
});
};
/**
+5 -13
View File
@@ -1,8 +1,9 @@
import { errorToConsole } from "./basic";
import { errorToConsole } from './basic';
import { Timer } from './timer';
export class MicrophoneController {
protected _stream?: MediaStream | null;
protected _timerID: number | null = null;
protected _timer = new Timer();
// We keep mute state separate from the stream state so that mute/unmute can
// be expressed before the stream is created -- and when it's create it will
@@ -68,20 +69,11 @@ export class MicrophoneController {
return !this._stream || this._stream.getTracks().every((track) => !track.enabled);
}
protected _clearTimer(): void {
if (this._timerID) {
window.clearTimeout(this._timerID);
this._timerID = null;
}
}
protected _startTimer(): void {
if (this._disconnectSeconds) {
this._clearTimer();
this._timerID = window.setTimeout(() => {
this._clearTimer();
this._timer.start(this._disconnectSeconds, () => {
this.disconnect();
}, this._disconnectSeconds * 1000);
});
}
}
}
+29
View File
@@ -0,0 +1,29 @@
export class Timer {
protected _timer: number | null = null;
public stop(): void {
if (this._timer) {
window.clearTimeout(this._timer);
this._timer = null;
}
}
public isRunning(): boolean {
return this._timer !== null;
}
public start(seconds: number, func: () => void): void {
this.stop();
this._timer = window.setTimeout(() => {
this._timer = null;
func();
}, seconds * 1000);
}
public startRepeated(seconds: number, func: () => void): void {
this.stop();
this._timer = window.setInterval(() => {
func();
}, seconds * 1000);
}
}