This repository was archived by the owner on Dec 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
83 lines (73 loc) · 1.95 KB
/
index.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
78
79
80
81
82
83
export type ScheduledTask = () => void;
export type StopFlushUpdates = () => void;
export type Scheduler = {
tick: Promise<void>;
enqueue: (task: ScheduledTask) => void;
flush: () => void;
flushSync: () => void;
onBeforeFlush: (callback: () => void) => StopFlushUpdates;
onFlush: (callback: () => void) => StopFlushUpdates;
};
/**
* Creates a scheduler which batches tasks and runs them in the microtask queue.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide}
* @example
* ```ts
* const scheduler = createScheduler();
*
* // Queue tasks.
* scheduler.enqueue(() => {});
* scheduler.enqueue(() => {});
*
* // Schedule a flush - can be invoked more than once.
* scheduler.flush();
*
* // Wait for flush to complete.
* await scheduler.tick;
* ```
*/
export function createScheduler(): Scheduler {
const queue = new Set<ScheduledTask>();
const microtask = Promise.resolve();
const beforeCallbacks = new Set<() => void>();
const afterCallbacks = new Set<() => void>();
const queueTask = typeof queueMicrotask !== 'undefined' ? queueMicrotask : microtask.then;
const enqueue = (task: ScheduledTask) => {
queue.add(task);
scheduleFlush();
};
let flushing = false;
const scheduleFlush = () => {
if (!flushing) {
flushing = true;
queueTask(flush);
}
};
const flush = () => {
runAll(beforeCallbacks);
for (const task of queue) {
task();
queue.delete(task);
}
flushing = false;
runAll(afterCallbacks);
};
return {
tick: microtask,
enqueue,
flush: scheduleFlush,
flushSync: flush,
onBeforeFlush: hook(beforeCallbacks),
onFlush: hook(afterCallbacks),
};
}
function hook(callbacks: Set<() => void>) {
return (callback: () => void) => {
callbacks.add(callback);
return () => callbacks.delete(callback);
};
}
function runAll(callbacks: Set<() => void>) {
for (const callback of callbacks) callback();
}