Scheduling work on the main thread
The main thread draws the page, runs your JavaScript and dispatches input, one task at a time, so a long task delays the next click and frame. Scheduling is splitting, ordering and offloading work so the visible part lands first.
What it is
The main thread of a browser tab is built around its event loop: the same thread draws pending changes to the document, runs the page's JavaScript, and takes input events and delivers them to their targets. It handles one task at a time. Any task that runs longer than 50 ms counts as a long task, and the part past 50 ms is its blocking period. While a task of any length runs, interactions wait; a long enough task makes the page feel stuck, and when the task was started by a click the delay shows up as a poor Interaction to Next Paint.
JavaScript runs to completion: a task runs to its end before anything else on the main thread gets a turn, which is why a setTimeout callback can't fire until the code that scheduled it has returned. Scheduling work on the main thread means deciding, for each piece of work, which task it belongs in and when that task should run. Four levers cover most cases: split a long job into short tasks, order tasks by how much the person is waiting on them, align visual updates with the frame, and offload pure computation to a worker.
Splitting works by yielding: you stop, hand control back to the browser so it can run anything more urgent, and continue in a later task. The old way is setTimeout(fn, 0), which moves the callback into a separate task; the cost is that the task joins the end of the queue behind whatever else is waiting, and once timeouts nest five deep the browser applies a 4 ms minimum. scheduler.yield() is the API built for this: it returns a promise that resolves in a future task, so the code after await scheduler.yield() runs there, and that continuation is prioritized ahead of other tasks of the same kind, so a third-party script's task doesn't cut in between your chunks. At the time of reading it was in Chrome and Edge from version 129 and Firefox from 142, with no Safari support, so it needs a fallback to a timeout.
Ordering uses scheduler.postTask(fn, { priority }), which queues a task with one of three priorities: user-blocking for work the person is stuck behind, such as drawing the part of the page they're using or answering their input; user-visible, the default, for work they'll see but aren't blocked on; and background for work that isn't time-critical, like logging. The scheduler runs tasks in priority order and, within a priority, in the order they were added. A TaskController lets you abort a task or change its priority after posting, so an image fetch can start as background and move up to user-visible when its slot scrolls into view. The scheduler object exists in both windows and workers.
function yieldToMain(): Promise<void> {
const s = (globalThis as any).scheduler;
if (s?.yield) return s.yield(); // continuation keeps its place
return new Promise((done) => setTimeout(done, 0)); // joins the end of the queue
}
async function runChunked(jobs: Array<() => void>, budgetMs = 50) {
let sliceStart = performance.now();
for (const job of jobs) {
job();
if (performance.now() - sliceStart > budgetMs) {
await yieldToMain(); // a chance for input and paint
sliceStart = performance.now();
}
}
}
// What the person is looking at goes first; the rest queues behind it.
scheduler.postTask(() => runChunked(visibleJobs), { priority: 'user-blocking' });
scheduler.postTask(() => runChunked(offscreenJobs), { priority: 'background' });
// One DOM write per frame, carrying the newest state.
let queued: State | null = null;
function drawLater(state: State) {
const idle = queued === null;
queued = state;
if (idle) requestAnimationFrame(() => { paint(queued!); queued = null; });
}Aligning with the frame means putting DOM writes in requestAnimationFrame, which calls you once before the next repaint, at a rate that generally follows the display's refresh rate (60 Hz is the most common). Each callback runs once, so an animation has to request the next frame from inside it, and most browsers pause these callbacks in background tabs. The pattern in the code above collapses many state changes into one draw per frame: pointer events can arrive faster than frames, and drawing each one is wasted work.
Offloading moves CPU-bound work to a Web Worker, a script on a separate thread that runs without interfering with the page's interface and can make its own fetch calls. A worker has no direct access to the DOM. The two sides talk with postMessage, and by default the data is copied rather than shared (serialized on one side and rebuilt on the other), though certain objects can be transferred or explicitly shared instead. That makes a worker a fit for computation whose input and output are small relative to the work, and the main thread still does the drawing.
When to use it
Reach for scheduling whenever one user action fans out into far more work than fits in a frame: a dashboard page that has to lay out a hundred widgets, a spreadsheet where one edit invalidates thousands of formulas, a map that must redraw while the finger is still moving. Our advice is to say the order out loud before the mechanism: first the response the person is waiting for (the typed character, the moved map, the edited cell), then the parts of the page they can see, then everything off screen, then background work. Each boundary between those groups is a place to yield or a change of priority.
Chunk a long loop when it would run past 50 ms. Yielding isn't free, so the runner above does a batch of jobs and yields once the slice has been running longer than its budget, rather than after each job; 50 ms is a common budget aimed at keeping each slice near the long-task line (a single job that runs long still overshoots it), and you can lower it to favor responsiveness over total time. Yield between work the person can see and work they can't: web.dev's advice is to let two updates that both matter to the interface run together and to yield after them, before the work nobody is watching.
Use priorities when the jobs are independent and some matter more than others. Widgets in the viewport are user-blocking or user-visible; widgets below the fold are background, and a TaskController can raise one when it scrolls into view. Since pending tasks run in priority order first and arrival order second, posting the off-screen work early usually doesn't push the on-screen work back, though a background chunk that is already running finishes before the scheduler picks the next task.
Use requestAnimationFrame when the output is pixels and the input is a stream: dragging, panning, resizing, scrolling a custom surface. Record the latest pointer position as events arrive, and let the frame callback draw it once. Use requestIdleCallback for work that helps later but nobody is waiting for: warming a cache, prefetching the next tile, trimming history. The callback receives an IdleDeadline whose timeRemaining() tops out at 50 ms and is often less, so do a small piece and re-request. Pass a timeout for anything that must happen eventually, because on a busy page idle callbacks may not run at all without one.
Move work to a worker when it's pure computation that would take long even when chunked: parsing a large payload, walking a formula dependency graph, clustering or projecting thousands of map points. Send the inputs, receive the results, and let the main thread do the DOM update, ideally in a frame callback. Because message data is usually copied, send what the worker needs and get back what the page needs, not the whole model each way.
When not to
Don't chunk work that already fits in a frame. Each yield has overhead, and when individual jobs are tiny the yielding and resuming can cost more than the jobs; a loop that finishes in a few milliseconds is better left as it is. The same goes for a single setTimeout(fn, 0) around a whole 600 ms job: it moves the long task later so a spinner can paint first, but the task is just as long when it runs.
Don't yield in the middle of one visible change. If two steps both update what the person sees, a yield between them lets a frame paint the half-done state; run them together and yield afterward. And don't skip yields based on isInputPending(): web.dev no longer recommends it, because it can report no input when there was some, and animations need the main thread as much as input does.
Don't put anything the person is waiting for into requestIdleCallback, and don't change the DOM from it. By the time an idle callback runs the current frame has been drawn and layout is settled, so a layout-affecting change there can force the browser into recalculation it might otherwise have skipped; schedule DOM changes from requestAnimationFrame instead. Adding a timeout to force the callback is a trade: it makes the work run on time at the price of possible stutter.
Don't hand a worker a DOM job. A worker can't manipulate the document, so building ten thousand rows there means it computes the data and the main thread still inserts the elements. And a job whose input or output is a large object graph is copied on each message unless you transfer or share it, and that copy can erase the gain for short tasks. Timers aren't a scheduling tool for hidden tabs either: browsers throttle setTimeout in inactive tabs (Firefox desktop applies a minimum of one second), so work that must keep pace there needs a different design.
Compared
| Tool | What it does | Reach for it when | What it costs |
|---|---|---|---|
| Runs the callback in a separate task at the end of the queue |
| Other queued tasks run first; nested timers get a 4 ms minimum after five levels |
| Pauses, and the continuation runs in a later task ahead of other similar tasks | You're splitting one long job and want its chunks to stay in order | Chrome and Edge 129+, Firefox 142+, no Safari when read, so it needs a fallback |
| Queues a new task as | Independent jobs of different importance, such as on-screen and off-screen widgets | Feature-test it before relying on it; three coarse levels, so finer ordering is yours to build |
| Calls back once before the next repaint, at the display's refresh rate | The output is visual and the input is a stream of events | Runs once per request and pauses in background tabs; not for non-visual work |
| Runs when the browser is idle, with up to 50 ms of | Prefetching, cache warming and cleanup that nobody is waiting on | May not run without a |
Web Worker | Runs a script on another thread, talking through messages whose data is copied unless transferred or shared | CPU-bound computation with small inputs and outputs | No DOM access; a large message that isn't transferred pays for a copy |
In a picture
Step 1 of 4
One task does it all
A click starts a function that does the whole job. The frame can't paint and the next input can't be handled until the task ends, however long it takes.