requestIdleCallback(callback, { timeout }) asks the browser to run callback when its event loop is idle, and returns a handle for cancelIdleCallback().
When it runs. The HTML event loop starts an idle period only when no task is runnable. Its deadline is the earliest of:
- 50 ms after the idle period started, so input arriving mid-callback can still be handled within 100 ms;
- the next timer's due time;
- the next expected frame, when animation frame callbacks or other rendering updates are pending.
Callbacks registered before the period started then run in order, each as its own task, until the deadline passes. One registered during the period waits for the next period, so a callback can safely re-register itself.
The IdleDeadline argument. timeRemaining() returns the milliseconds left, never negative; check it between small units of work. didTimeout is true when the callback ran because its timeout expired.
What it doesn't guarantee:
- That it runs. A page that always has a task queued may never be idle; the spec accepts postponing callbacks "for a potentially unbounded amount of time". The
timeoutoption bounds that: once it expires, a task runs the callback withdidTimeouttrueandtimeRemaining()0. - How often. Browsers may throttle idle periods for hidden pages; the spec suggests one every 10 seconds.
- A long budget. In three headless runs, Chrome 156 gave 50 ms on an idle page and about 16 ms with an animation running; Firefox 159 never gave more than 8.6 ms.
Use it for work that can wait: analytics, prefetching, cache warming. Avoid DOM changes in it: their style and layout cost is hard to predict. Safari has requestIdleCallback only in Technology Preview behind a flag, so feature-detect and fall back to setTimeout.