10LOC

#requestidlecallback

Web Platformintermediate

requestIdleCallback for scheduling non-urgent work

type IdleCallback = (deadline: IdleDeadline) => void;

const runOnNextTick = (callback: IdleCallback) => {
  const start = performance.now();
  setTimeout(() => callback({ didTimeout: false, timeRemaining: () => Math.max(0, 50 - (performance.now() - start)) }), 1);

Run analytics, prefetching, or cache warming only when the browser has real spare time, with a fallback for the one major browser that never shipped this API.