Line data Source code
1 : /**
2 : * Cross-browser async utilities for scheduling tasks during browser idle time
3 : * with proper fallbacks for browsers that don't support requestIdleCallback.
4 : *
5 : * Implementation based on:
6 : * https://github.com/microsoft/vscode/blob/main/src/vs/base/common/async.ts
7 : */
8 :
9 : interface IdleDeadline {
10 : didTimeout: boolean
11 : timeRemaining(): number
12 : }
13 :
14 : interface IDisposable {
15 : dispose(): void
16 : }
17 : type GlobalWindow = typeof globalThis
18 :
19 : /**
20 : * Internal implementation function that handles the actual scheduling logic.
21 : * Uses feature detection to determine whether to use native requestIdleCallback
22 : * or fall back to setTimeout-based implementation.
23 : */
24 2355 : let _runWhenIdle: (
25 : targetWindow: GlobalWindow,
26 : callback: (idle: IdleDeadline) => void,
27 : timeout?: number
28 : ) => IDisposable
29 :
30 : /**
31 : * Execute the callback during the next browser idle period.
32 : * Falls back to setTimeout-based scheduling in browsers without native support.
33 : */
34 2355 : export let runWhenGlobalIdle: (
35 2355 : callback: (idle: IdleDeadline) => void,
36 : timeout?: number
37 : ) => IDisposable
38 :
39 : // Self-invoking function to set up the idle callback implementation
40 : ;(function () {
41 2355 : const safeGlobal: GlobalWindow = globalThis
42 :
43 2355 : if (
44 : typeof safeGlobal.requestIdleCallback !== 'function' ||
45 : typeof safeGlobal.cancelIdleCallback !== 'function'
46 : ) {
47 : // Fallback implementation for browsers without native support (e.g., Safari)
48 0 : _runWhenIdle = (_targetWindow, runner, _timeout?) => {
49 0 : setTimeout(() => {
50 0 : if (disposed) {
51 0 : return
52 : }
53 :
54 : // Simulate IdleDeadline - give 15ms window (one frame at ~64fps)
55 0 : const end = Date.now() + 15
56 : const deadline: IdleDeadline = {
57 : didTimeout: true,
58 : timeRemaining() {
59 0 : return Math.max(0, end - Date.now())
60 : }
61 : }
62 :
63 0 : runner(Object.freeze(deadline))
64 : })
65 :
66 0 : let disposed = false
67 0 : return {
68 : dispose() {
69 0 : if (disposed) {
70 0 : return
71 : }
72 0 : disposed = true
73 : }
74 : }
75 : }
76 : } else {
77 : // Native requestIdleCallback implementation
78 2355 : _runWhenIdle = (targetWindow: typeof safeGlobal, runner, timeout?) => {
79 4710 : const handle: number = targetWindow.requestIdleCallback(
80 : runner,
81 : typeof timeout === 'number' ? { timeout } : undefined
82 : )
83 :
84 4710 : let disposed = false
85 4710 : return {
86 : dispose() {
87 2362 : if (disposed) {
88 0 : return
89 : }
90 2362 : disposed = true
91 2362 : targetWindow.cancelIdleCallback(handle)
92 : }
93 : }
94 : }
95 : }
96 :
97 2355 : runWhenGlobalIdle = (runner, timeout) =>
98 : _runWhenIdle(globalThis, runner, timeout)
99 : })()
|