Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

requestIdleCallback — work during idle periods

requestIdleCallback schedules nonurgent work during browser idle periods. Its callback receives an estimated time budget, but must split work and yield control itself.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const handle = window.requestIdleCallback(callback, { timeout: 1000 });
// callback receives an IdleDeadline: deadline.timeRemaining(), deadline.didTimeout
window.cancelIdleCallback(handle);

window.requestIdleCallback(callback, options) schedules nonurgent work once on the page's event loop, not on a separate thread. The returned handle lets window.cancelIdleCallback(handle) cancel a pending invocation.

The callback receives an IdleDeadline: timeRemaining() reports the estimated remaining milliseconds, never below zero. Split work into small units and reschedule leftovers; the browser does not automatically interrupt a lengthy operation.

Without timeout, waiting can be unbounded. A positive timeout in milliseconds queues a task after that interval, rather than guaranteeing an exact execution time. didTimeout identifies execution through this path; timeRemaining() is then zero. The example processes only one item per invocation in that case.

This is a Window Web API, not an ECMAScript feature; having Node 24 does not establish support. Check availability in the target browser. The source is a W3C draft, not a browser compatibility table.

Examples

(() => {
  if (typeof window.requestIdleCallback !== "function") {
    console.log("requestIdleCallback unavailable");
    return;
  }

  const items = [1, 2, 3, 4];
  let index = 0;
  let sum = 0;

  function work(deadline) {
    let processed = 0;
    while (index < items.length &&
           (deadline.timeRemaining() > 0 ||
            (deadline.didTimeout && processed === 0))) {
      sum += items[index++];
      processed++;
    }
    if (index < items.length) {
      window.requestIdleCallback(work, { timeout: 1000 });
    } else {
      console.log(sum);
    }
  }

  window.requestIdleCallback(work, { timeout: 1000 });
})();

Result

10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources