Code

Browser Web APIs

CDEFGHIJKLMNOPQRSTUVWXYZ

Background Tasks API

Provides a cooperative scheduling mechanism via requestIdleCallback() that lets the browser invoke a callback during idle periods — time frames where no urgent tasks are pending. Ideal for non-critical background work that should not block animations or user interactions.

MDN Reference

Key Interfaces
  • requestIdleCallback(callback, options?) — Schedules a callback to run during the next idle period. Returns a numeric handle.
  • cancelIdleCallback(handle) — Cancels a previously registered idle callback.
  • IdleDeadline.timeRemaining() — Returns the estimated remaining idle time in milliseconds for the current frame.
  • IdleDeadline.didTimeouttrue if the callback was invoked because the timeout option expired.
Example — Process a task queue during idle time

Break a large workload into chunks and process items only while the browser is idle, yielding back to the event loop between frames.

const taskQueue = Array.from({ length: 500 }, (_, i) => i);

function processTasks(deadline) {
  while (taskQueue.length > 0 && deadline.timeRemaining() > 0) {
    const task = taskQueue.shift();
    performWork(task); // your non-critical work here
  }

  if (taskQueue.length > 0) {
    // More work left — schedule the next idle callback
    requestIdleCallback(processTasks);
  }
}

requestIdleCallback(processTasks);
Example — Timeout fallback

Use timeout to guarantee the callback runs within a maximum wait time, even if the browser never becomes truly idle. Check didTimeout to decide whether to do a smaller unit of work.

requestIdleCallback(
  (deadline) => {
    if (deadline.didTimeout) {
      // Forced run — do minimal work to avoid jank
      processOneTask();
    } else {
      // Plenty of idle time — process as much as possible
      while (deadline.timeRemaining() > 5 && taskQueue.length) {
        processOneTask();
      }
    }
  },
  { timeout: 2000 } // run within 2 seconds regardless
);
Example — Cancel an idle callback
const handle = requestIdleCallback(() => {
  console.log('Running background analytics...');
  sendAnalytics();
});

// Cancel before it runs (e.g. user navigated away)
cancelIdleCallback(handle);