|
6 | 6 | * found in the LICENSE file at https://angular.io/license |
7 | 7 | */ |
8 | 8 |
|
9 | | -import {global} from './global'; |
| 9 | +import {noop} from './noop'; |
10 | 10 |
|
11 | 11 | /** |
12 | 12 | * Gets a scheduling function that runs the callback after the first of setTimeout and |
@@ -35,38 +35,40 @@ import {global} from './global'; |
35 | 35 | * @returns a function to cancel the scheduled callback |
36 | 36 | */ |
37 | 37 | export function scheduleCallbackWithRafRace(callback: Function): () => void { |
38 | | - let executeCallback = true; |
39 | | - setTimeout(() => { |
40 | | - if (!executeCallback) { |
41 | | - return; |
| 38 | + let timeoutId: number; |
| 39 | + let animationFrameId: number; |
| 40 | + function cleanup() { |
| 41 | + callback = noop; |
| 42 | + try { |
| 43 | + if (animationFrameId !== undefined && typeof cancelAnimationFrame === 'function') { |
| 44 | + cancelAnimationFrame(animationFrameId); |
| 45 | + } |
| 46 | + if (timeoutId !== undefined) { |
| 47 | + clearTimeout(timeoutId); |
| 48 | + } |
| 49 | + } catch { |
| 50 | + // Clearing/canceling can fail in tests due to the timing of functions being patched and unpatched |
| 51 | + // Just ignore the errors - we protect ourselves from this issue by also making the callback a no-op. |
42 | 52 | } |
43 | | - executeCallback = false; |
| 53 | + } |
| 54 | + timeoutId = setTimeout(() => { |
44 | 55 | callback(); |
45 | | - }); |
46 | | - if (typeof global['requestAnimationFrame'] === 'function') { |
47 | | - global['requestAnimationFrame'](() => { |
48 | | - if (!executeCallback) { |
49 | | - return; |
50 | | - } |
51 | | - executeCallback = false; |
| 56 | + cleanup(); |
| 57 | + }) as unknown as number; |
| 58 | + if (typeof requestAnimationFrame === 'function') { |
| 59 | + animationFrameId = requestAnimationFrame(() => { |
52 | 60 | callback(); |
| 61 | + cleanup(); |
53 | 62 | }); |
54 | 63 | } |
55 | 64 |
|
56 | | - return () => { |
57 | | - executeCallback = false; |
58 | | - }; |
| 65 | + return () => cleanup(); |
59 | 66 | } |
60 | 67 |
|
61 | 68 | export function scheduleCallbackWithMicrotask(callback: Function): () => void { |
62 | | - let executeCallback = true; |
63 | | - queueMicrotask(() => { |
64 | | - if (executeCallback) { |
65 | | - callback(); |
66 | | - } |
67 | | - }); |
| 69 | + queueMicrotask(() => callback()); |
68 | 70 |
|
69 | 71 | return () => { |
70 | | - executeCallback = false; |
| 72 | + callback = noop; |
71 | 73 | }; |
72 | 74 | } |
0 commit comments