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.

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.
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);index document 1
index document 2
index document 3The 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.
requestIdleCallback(
(deadline) => {
console.log("timed out:", deadline.didTimeout);
},
{ timeout: 2000 },
);timed out: falseOn 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.
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);[ '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.
try {
const value = await scheduler.postTask(() => 21 * 2, { priority: "background" });
console.log("result:", value);
} catch (error) {
console.log("task failed:", error.message);
}result: 42Cancelling and changing priority
A TaskController creates a signal that cancels the task, and it can also change the priority later.
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));AbortErrorcontroller.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
requestIdleCallback | scheduler.postTask | |
|---|---|---|
| Promise for the result | No | Yes |
| Priorities | One (idle) | Three, plus changeable |
| Cancel | cancelIdleCallback with an id | AbortSignal |
| Knows how much time is left | Yes, timeRemaining() | No |
| Guarantees it runs | Only with timeout | Yes, eventually |
| Starves under load | Possible | Background 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.
const runWhenIdle =
globalThis.requestIdleCallback ??
((callback) => setTimeout(() => callback({ timeRemaining: () => 10, didTimeout: true }), 1));
runWhenIdle(() => console.log("ran"));ranThe 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.


