JavaScript Reference ยท Promises and Async
The requestIdleCallback() function
Reference for requestIdleCallback(): running low-priority work when the browser is idle, the deadline object, the timeout option, cancelling, and fallbacks.
requestIdleCallback() queues a function to run when the browser has nothing more urgent to do, such as between frames or while waiting for input. It is meant for low-priority background work: analytics, prefetching, building search indexes, or processing a long list in small slices without hurting responsiveness.
Your callback receives a deadline object telling you how much idle time is left in this slot. Do a little work, check the deadline, and schedule another callback if there is more to do.
requestIdleCallback((deadline) => { while (deadline.timeRemaining() > 0 && queue.length) { process(queue.shift()); } });
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
const id = requestIdleCallback(callback); const id2 = requestIdleCallback(callback, { timeout: 2000 }); cancelIdleCallback(id);
| Name | Description |
|---|---|
callback |
Function called with an IdleDeadline object. |
options.timeout |
Optional. Milliseconds after which the callback is queued as a normal task even if the browser is never idle. |
The IdleDeadline object has two members:
| Member | Description |
|---|---|
timeRemaining() |
Milliseconds of idle time left in this slot (never negative). Browsers cap it at about 50 ms. |
didTimeout |
true if the callback runs because the timeout option expired rather than because the browser was idle. |
Return value: a positive integer id for cancelIdleCallback().
Usage notes
- Check
timeRemaining()in a loop and stop when it nears zero, then schedule another callback for the rest. A callback that overruns defeats the purpose. - Never touch the DOM heavily in an idle callback; layout changes force work at the start of the next frame. Do computation there and apply visible changes in
requestAnimationFrame(). - Without
timeout, it may never run on a permanently busy page. Add a timeout for work that must eventually happen. - Not for time-critical work. Anything the user is waiting for belongs in normal code, not here.
- Feature-detect it. Some browsers, notably Safari, have not shipped it, so fall back to
setTimeout()as in the first example. Not available in Node.js. - Order is not guaranteed between idle callbacks scheduled from different places beyond first-come, first-served.
Browser support
Supported in Chromium-based browsers and Firefox, but not in every browser, so feature-detect and keep a setTimeout() fallback. Check a compatibility table before relying on it.