forked from dust-books/dust-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclock.ts
42 lines (37 loc) · 1.05 KB
/
clock.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
/**
* Manages tasks that are intended to run at given interval.
*/
export interface TimerManager {
/**
* Register a function to run on a timer.
* @param f Function to run
* @param interval interval at which to run the function
*
* @returns the intervalId -- can be cleared with clearInterval if necessary.
*/
registerTimer(f: () => void, interval: number): number;
/**
* Remove a timer associated with the provided intervalId
* @param intervalId The intervalId to clear
*/
removeTimer(intervalId: number): void;
}
export class DustTimerManager implements TimerManager {
private timers = new Set<number>();
registerTimer(f: () => void, interval: number): number {
const intervalId = setInterval(f, interval);
this.timers.add(intervalId);
return intervalId;
}
removeTimer(intervalId: number): void {
if (this.timers.has(intervalId)) {
clearInterval(intervalId);
this.timers.delete(intervalId);
}
}
clearAll(): void {
for (const id of this.timers) {
this.removeTimer(id);
}
}
}