Debian Codegraph @

node/rxjs/src/internal/util/Immediate.ts

raw
1 let nextHandle = 1;
2 // The promise needs to be created lazily otherwise it won't be patched by Zones
3 let resolved: Promise<any>;
4 const activeHandles: { [key: number]: any } = {};
5
6 /**
7 * Finds the handle in the list of active handles, and removes it.
8 * Returns `true` if found, `false` otherwise. Used both to clear
9 * Immediate scheduled tasks, and to identify if a task should be scheduled.
10 */
11 function findAndClearHandle(handle: number): boolean {
12 if (handle in activeHandles) {
13 delete activeHandles[handle];
14 return true;
15 }
16 return false;
17 }
18
19 /**
20 * Helper functions to schedule and unschedule microtasks.
21 */
22 export const Immediate = {
23 setImmediate(cb: () => void): number {
24 const handle = nextHandle++;
25 activeHandles[handle] = true;
26 if (!resolved) {
27 resolved = Promise.resolve();
28 }
29 resolved.then(() => findAndClearHandle(handle) && cb());
30 return handle;
31 },
32
33 clearImmediate(handle: number): void {
34 findAndClearHandle(handle);
35 },
36 };
37
38 /**
39 * Used for internal testing purposes only. Do not export from library.
40 */
41 export const TestTools = {
42 pending() {
43 return Object.keys(activeHandles).length;
44 }
45 };