What is requestIdleCallback and how is it used for performance?

Answer

requestIdleCallback schedules a callback to run during the browser's idle time — when the main thread has no higher-priority work (rendering, event handling). Use it for non-critical, deferrable work that can be delayed without affecting user experience. Usage: requestIdleCallback((deadline) => { while (deadline.timeRemaining() > 0 && tasks.length > 0) { processTask(tasks.shift()); } if (tasks.length > 0) requestIdleCallback(processNextBatch); }). deadline.timeRemaining(): remaining idle time in milliseconds. deadline.didTimeout: whether the timeout expired. Options: { timeout: 2000 } — force execution after 2 seconds even if not idle. Use cases: analytics event batching, prefetching next page data, pre-computing derived state, sending logs, lazy initialization of non-critical modules. Limitations: not reliable for critical work (may not run for seconds on busy pages). Browser support is good but Safari was late to support it. The newer Scheduler API (scheduler.postTask()) provides more granular priority control. For React 18, useTransition and useDeferredValue use the scheduler internally.