Skip to content
jshacks.dev
Async

requestIdleCallback and scheduler.postTask

Compare requestIdleCallback and scheduler.postTask in the browser, see how priorities and idle deadlines work and which one to pick for background work.

6 min read
Summarize in AI
Flat illustration of a clock over a calendar of scheduled tasks, with the JavaScript, Google Chrome, npm and Node.js logos.

Browsers give you two ways to say that some work is not urgent. requestIdleCallback waits until the main thread has nothing better to do and hands you a deadline. scheduler.postTask lets you queue a task with a named priority and an abort signal, and the browser orders it against its own work. They solve related problems with different promises, and neither is available everywhere, so choosing between them includes a support decision. This post explains how each works, with the exact behavior you can rely on in current Chrome and Edge, where Safari and Firefox stand and how to write code that degrades safely. It is aimed at anyone moving analytics, prefetching, indexing or cache warming off the critical path of a page.

requestIdleCallback

You pass a callback, and the browser calls it during an idle period, such as the time left in a frame after rendering finishes or when nothing is happening at all. The callback receives an IdleDeadline object with timeRemaining(), which returns how many milliseconds the browser will give you, and didTimeout.

JavaScript
function doBackgroundWork(deadline) {
  while (deadline.timeRemaining() > 1 && queue.length > 0) {
    const job = queue.shift();
    job();
  }

  if (queue.length > 0) {
    requestIdleCallback(doBackgroundWork);
  }
}

const queue = [
  () => console.log("index document 1"),
  () => console.log("index document 2"),
  () => console.log("index document 3"),
];

requestIdleCallback(doBackgroundWork);
Text
index document 1
index document 2
index document 3

The pattern is a work loop: do a unit, check the remaining time, and reschedule if jobs remain. During a busy page the browser may offer only a few milliseconds per idle period, and during a quiet one up to 50 ms, a cap chosen so that a user input arriving during the work still feels responsive. The number of idle periods you get is not under your control, and on a page that is constantly busy it may be none at all.

The timeout option

Without a timeout, a callback might never run. Passing { timeout: ms } makes the browser run it by then, with didTimeout set to true and no promise of remaining time.

JavaScript
requestIdleCallback(
  (deadline) => {
    console.log("timed out:", deadline.didTimeout);
  },
  { timeout: 2000 },
);
Text
timed out: false

On an idle page, the callback runs right away and didTimeout is false. On a busy page it would run at the two second mark with didTimeout true, and the code should then do a small, bounded amount of work, since the browser is not being generous.

scheduler.postTask

scheduler.postTask(callback, options) returns a promise for the callback's result and takes a priority of "user-blocking", "user-visible" (the default) or "background", a delay in milliseconds and a signal.

JavaScript
const results = [];

scheduler.postTask(() => results.push("background"), { priority: "background" });
scheduler.postTask(() => results.push("user-visible"), { priority: "user-visible" });
scheduler.postTask(() => results.push("user-blocking"), { priority: "user-blocking" });

setTimeout(() => console.log(results), 50);
Text
[ 'user-blocking', 'user-visible', 'background' ]

The three tasks were queued in the opposite order of their priority, and they ran from most urgent to least. Within the same priority, tasks run in the order they were posted. Because the call returns a promise, you can await it and handle errors with try/catch.

JavaScript
try {
  const value = await scheduler.postTask(() => 21 * 2, { priority: "background" });
  console.log("result:", value);
} catch (error) {
  console.log("task failed:", error.message);
}
Text
result: 42

Cancelling and changing priority

A TaskController creates a signal that cancels the task, and it can also change the priority later.

JavaScript
const controller = new TaskController({ priority: "background" });

const task = scheduler.postTask(() => console.log("never runs"), {
  signal: controller.signal,
});

controller.abort();

task.catch((error) => console.log(error.name));
Text
AbortError

controller.setPriority("user-blocking") raises the priority of every task using that signal, which is the right tool when work started as a prefetch becomes necessary because the user clicked.

The differences that matter

requestIdleCallbackscheduler.postTask
Promise for the resultNoYes
PrioritiesOne (idle)Three, plus changeable
CancelcancelIdleCallback with an idAbortSignal
Knows how much time is leftYes, timeRemaining()No
Guarantees it runsOnly with timeoutYes, eventually
Starves under loadPossibleBackground tasks run when nothing else is queued

The most important row is the third from the bottom. requestIdleCallback tells you how long you may run, and postTask does not, so each task must be small enough to be harmless on its own. If you want to process a long list in slices that adapt to the available time, the idle deadline is the better fit. If you want an ordering of important and unimportant work, with a promise and cancellation, postTask is the better fit.

Support and fallback

requestIdleCallback is available in Chromium browsers and Firefox, and Safari has long kept it behind a flag, so a portable page needs a fallback. scheduler.postTask is available in Chromium browsers and Firefox, and Safari support has lagged, so feature detection is required here too.

JavaScript
const runWhenIdle =
  globalThis.requestIdleCallback ??
  ((callback) => setTimeout(() => callback({ timeRemaining: () => 10, didTimeout: true }), 1));

runWhenIdle(() => console.log("ran"));
Text
ran

The fallback uses a short timeout and fakes the deadline object with a fixed budget, which is the same approach polyfills take. For postTask, a fallback can map priorities to queueMicrotask for user-blocking, setTimeout(0) for user-visible and the idle fallback above for background.

What to put in each

Good candidates for background priority or idle time: sending analytics beacons, warming a cache, prefetching likely next pages, building a search index for the current page, sorting a long list for a feature the user has not opened yet. Poor candidates: anything that must finish for the user to see a correct page, anything that touches the DOM in a way that changes layout (which still forces work at the next frame) and anything that must happen in a given order relative to user input.

Keep the unit of work small. A callback that runs for 40 ms has delayed any input that arrived at the start of it by 40 ms, whether it was scheduled as idle or not. Aim for units of a few milliseconds, check the time between them and be willing to give up the rest of the slice.

A practical split for a real page

Consider a page with a product list. The user's first interaction depends on the list rendering, so that stays on the main path with no scheduling. The analytics beacon for the page view can go through postTask at background priority, since nobody notices if it is a second late. Prefetching the next page's data is a good fit for an idle callback with a timeout of a few seconds: do it if the browser is idle, and do it anyway if the user has lingered. Building a client-side search index over the visible items can run as a series of small idle slices, each checking timeRemaining() so it stops when the user starts scrolling.

The unifying idea is that you describe how urgent each piece of work is and let the browser order it. When you find yourself guessing delays for a timer, such as waiting 2000 ms because that "seems enough", an idle callback or a background task states the intent more honestly and adapts to a slow device.

Also inBrowser
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.