-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtimer.ts
65 lines (50 loc) · 1.22 KB
/
timer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
export class Timer {
private readonly callback: () => void;
private readonly delay: number;
private remaining: number;
private timerId: ReturnType<typeof setTimeout> | null = null;
private startTime: number | null = null;
private _status: 'stopped' | 'paused' | 'running' = 'stopped';
get status() {
return this._status;
}
private set status(status) {
this._status = status;
}
constructor(callback: () => unknown, delay: number) {
this.callback = callback;
this.delay = delay;
this.remaining = delay;
this.resume();
}
reset() {
this.clear();
this.remaining = this.delay;
this.status = 'stopped';
}
pause() {
if (this.timerId === null || this.startTime === null) {
return;
}
this.clear();
this.remaining -= Date.now() - this.startTime;
this.status = 'paused';
}
resume() {
if (this.timerId !== null) return;
this.startTime = Date.now();
this.clear();
this.timerId = setTimeout(() => {
this.reset();
this.callback();
}, this.remaining);
this.status = 'running';
}
private clear() {
if (this.timerId === null) {
return;
}
clearTimeout(this.timerId);
this.timerId = null;
}
}