All files / client/src/utils whenIdle.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 3/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22          521x   521x 533x 161x 161x 6x         372x 372x 11x      
// Defers low-priority work until the browser reports spare time. No shipping
// Safari or iOS version implements requestIdleCallback, so the timer branch is
// the path every Apple device takes rather than a legacy edge case: it gives
// no guarantee the main thread is free, but it still keeps the work off the
// critical path. Returns a cancel function
const FALLBACK_DELAY_MS = 2000;
 
export const whenIdle = (task: () => void): (() => void) => {
  if (typeof requestIdleCallback === "undefined") {
    const timeout = setTimeout(task, FALLBACK_DELAY_MS);
    return () => {
      clearTimeout(timeout);
    };
  }
 
  // eslint-disable-next-line compat/compat -- Guarded by the check above
  const handle = requestIdleCallback(task);
  return () => {
    cancelIdleCallback(handle);
  };
};