-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
scheduler.ts
77 lines (63 loc) · 1.59 KB
/
scheduler.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
66
67
68
69
70
71
72
73
74
75
76
77
interface SchedulerOptions {
deferEvents: boolean;
}
const defaultOptions: SchedulerOptions = {
deferEvents: false
};
export class Scheduler {
private processingEvent: boolean = false;
private queue: Array<() => void> = [];
private initialized = false;
// deferred feature
private options: SchedulerOptions;
constructor(options?: Partial<SchedulerOptions>) {
this.options = { ...defaultOptions, ...options };
}
public initialize(callback?: () => void): void {
this.initialized = true;
if (callback) {
if (!this.options.deferEvents) {
this.schedule(callback);
return;
}
this.process(callback);
}
this.flushEvents();
}
public schedule(task: () => void): void {
if (!this.initialized || this.processingEvent) {
this.queue.push(task);
return;
}
if (this.queue.length !== 0) {
throw new Error(
'Event queue should be empty when it is not processing events'
);
}
this.process(task);
this.flushEvents();
}
public clear(): void {
this.queue = [];
}
private flushEvents() {
let nextCallback: (() => void) | undefined = this.queue.shift();
while (nextCallback) {
this.process(nextCallback);
nextCallback = this.queue.shift();
}
}
private process(callback: () => void) {
this.processingEvent = true;
try {
callback();
} catch (e) {
// there is no use to keep the future events
// as the situation is not anymore the same
this.clear();
throw e;
} finally {
this.processingEvent = false;
}
}
}