Glossary / Idle callbacks

Idle callbacks

requestIdleCallback(callback) schedules low-priority work when the browser estimates there is idle time. It is intended for optional background work such as preparing caches or incremental non-urgent computation, not for work that must happen promptly. The API has limited availability and browser-specific behavior, so feature support and fallback strategy must be checked.

Deadline and chunking

The callback receives an IdleDeadline with timeRemaining() and didTimeout. Process small chunks while time remains, then schedule more work. A timeout option can ensure eventual execution, but the callback may then run under load and harm responsiveness. Do not assume every event-loop turn has idle time; busy pages may delay callbacks substantially.

Avoid DOM layout changes in idle callbacks; schedule visual changes with requestAnimationFrame. Do not put unbounded or unpredictable work there, and do not use it for required user-visible updates. A Promise resolved in an idle callback schedules microtasks that can consume the frame’s remaining budget. Use a task queue, worker, or server for essential/heavy work.

function processIdle(deadline) {
  while (deadline.timeRemaining() > 1 && pending.length) processOne(pending.shift());
  if (pending.length) requestIdleCallback(processIdle, { timeout: 2000 });
}

This API is not a hard real-time scheduler. Provide a fallback such as chunked setTimeout or a scheduler abstraction where necessary.

Interview questions

  1. What work suits idle callbacks? Low-priority, deferrable, chunkable background work.
  2. Does an idle callback have guaranteed timing? No; idle periods may be scarce.
  3. What does the timeout option guarantee? It requests eventual callback invocation, potentially under load; it is not a deadline for completion.
  4. Why avoid DOM mutations? They can trigger layout/paint work outside the ideal rendering phase.

References