-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout-latch.ts
More file actions
103 lines (89 loc) · 2.68 KB
/
timeout-latch.ts
File metadata and controls
103 lines (89 loc) · 2.68 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
export type TimeoutLatchConstructor = [timeoutMS: number, onTimeExhaustedCallback?: Function];
export class TimeoutLatch {
private timeLeftMS: number;
private isCancelled: boolean = false;
private _isTimeExhausted: boolean = false;
readonly timeoutMS: number;
private onTimeExhaustedCallbacks: Function[] = [];
private onResetCallbacks: Function[] = [];
constructor(...params: TimeoutLatchConstructor) {
this.timeoutMS = params[0];
this.timeLeftMS = this.timeoutMS;
if (params[1]) {
this.onTimeExhaustedCallbacks.push(params[1]);
}
}
reset() {
this.timeLeftMS = this.timeoutMS;
this.isCancelled = false;
this.isTimeExhausted = false;
this.runAllResetCallbacks();
}
reduceTimeLeft(
timeMS: number,
) {
if (this.isCancelled) {
console.warn('timeout-latch already cancelled!');
return;
}
if (this.isTimeExhausted) {
console.warn('timeLeft already exhausted!');
return;
}
this.timeLeftMS -= timeMS;
if (this.timeLeftMS <= 0) {
this.isTimeExhausted = true;
}
}
cancel() {
if (this.isCancelled) {
console.warn('timeout-latch already cancelled!');
return;
}
this.isCancelled = true;
}
get isDone(): boolean {
return this.isCancelled || this.isTimeExhausted;
}
private set isTimeExhausted(flag: boolean) {
this._isTimeExhausted = flag;
if (flag) {
this.onTimeExhausted();
}
}
private get isTimeExhausted() {
return this._isTimeExhausted;
}
private onTimeExhausted() {
this.runAllTimeExhaustedCallbacks();
}
registerOnTimeExhaustedCallback(callback: Function) {
this.onTimeExhaustedCallbacks.push(callback);
}
clearTimeExhaustedCallback(functionReference: Function) {
this.onTimeExhaustedCallbacks.splice(
this.onTimeExhaustedCallbacks.indexOf(functionReference),
1);
}
private runAllTimeExhaustedCallbacks() {
for (const callback of this.onTimeExhaustedCallbacks) {
callback();
}
}
registerOnResetCallback(callback: Function) {
this.onResetCallbacks.push(callback);
}
clearResetCallback(functionReference: Function) {
this.onResetCallbacks.splice(
this.onResetCallbacks.indexOf(functionReference),
1);
}
private runAllResetCallbacks() {
for (const callback of this.onResetCallbacks) {
setTimeout(
callback,
0
)
}
}
}