0% completed
The Main Thread and Long Tasks
On This Page
One Thread for Most of the Page
The Event Loop
Long Tasks
Input Delay
What Shortens the Wait
Using This in an Interview
Key Takeaways
Practice Questions
A tap on "Add to cart" waited 437 ms before the page's click code began to run. The click code is one line that stores a time. The tap came 106 ms into a 542 ms piece of work that sorted Basket's 4,000 products by price and formatted every price as currency.
That result was measured in headless Chrome 150 on a desktop with an AMD Ryzen 7 5800X, with the CPU slowed four times to approximate a mid-range phone. On the same page with nothing else running, the same tap waited 2 ms.
Nothing was wrong with the button. The page had one place to run code, and the sort was using it. The sections below describe how the browser shares that place between scripts, input and drawing, and why a single long piece of work makes the whole page stop responding.
One Thread for Most of the Page
The main thread runs the page's JavaScript, works out styles and layout, paints, and delivers every click and key press to the page. It does these one at a time, never two at once.
A few jobs happen elsewhere. The network stack downloads files on other threads, and the compositor thread combines painted layers, as described in How a Browser Turns HTML into Pixels. A Web Worker is a separate thread that a page can start to run JavaScript. A worker cannot touch the DOM, so it suits pure calculation such as sorting or parsing.
The Event Loop
The main thread runs a fixed cycle called the event loop. A task is one unit of work that the browser puts in a queue and runs from start to finish: running a script file, calling one click handler, calling one timer callback. Each turn of the loop does three things in order.
- Take the oldest waiting task and run it to the end. Nothing can interrupt it.
- Run every waiting microtask, including any that those microtasks add.
- If it is time for a new frame, update the rendering: run
requestAnimationFramecallbacks, then style, layout and paint.
A microtask is a smaller job that must run as soon as the current task ends, before anything else. Promise callbacks (.then and the code after await) and queueMicrotask create microtasks. A rendering opportunity is a moment when the browser may draw a new frame, about every 16.7 ms on a 60 Hz screen. The browser takes it only between tasks, never in the middle of one.
Look at where the tap enters: it joins the task queue, so it runs only when the loop comes back to step 1. Notice that the microtask step runs until its queue is empty, so code that keeps adding microtasks stops the loop from ever reaching the render step.
The sample prints the order of one script, one promise callback, and one timer with a delay of zero. The three lines below come from the sample page:
order.push('1. script') setTimeout(() => order.push('3. task (setTimeout 0)'), 0) Promise.resolve().then(() => order.push('2. microtask (promise)'))
Output:
event loop order: 1. script | 2. microtask (promise) | 3. task (setTimeout 0)
The promise callback was queued after the timer, but it ran first. The script was the current task, the promise callback was a microtask that ran as soon as that task ended, and the timer was a new task that waited for the next turn.
| Kind of work | Queue | Runs when | Example |
|---|---|---|---|
| Task | Task queue | One per turn of the loop | Script file, click handler, setTimeout callback |
| Microtask | Microtask queue | Right after the current task, all of them | Promise callback, queueMicrotask |
| Frame callback | Rendering step | Before the next frame is drawn | requestAnimationFrame |
Long Tasks
A long task is a task that holds the main thread for more than 50 ms. The limit comes from a response target of about 100 ms: when no task is longer than 50 ms, any input waits at most 50 ms to start, which leaves the other 50 ms for the page's own response.
Here is the work from the opening. It is ordinary product list code, written as one function:
function sortAndFormat() { return products.slice().sort((a, b) => a.price - b.price) .map((p) => p.price.toLocaleString('en-US', { style: 'currency', currency: 'USD' })) }
The sample timed it at full speed and with the CPU slowed four times:
Output:
sort and format 4,000 prices, full speed: 70 ms (median of 5) sort and format 4,000 prices, CPU 4x slower: 359 ms (median of 5) long tasks reported by the browser (ms): 537
At full speed the task is already over the 50 ms limit. On the slowed CPU it took about five times longer. The third line comes from the Long Tasks API, a PerformanceObserver of type longtask, which reports every task over 50 ms with its duration. It reported one task of 537 ms on the first of five fresh page loads.
Timings vary between runs. The same work took a median of 359 ms when it was repeated on one open page and a median of 542 ms on freshly loaded pages, so read each number as a size, not as a constant.
Input Delay
Input delay is the time between the user's input and the moment the page's handler for it starts to run. It is the first of three parts of a response: the delay, the handler's own work, and the time to draw the next frame.
The sample loaded the page five times. On each load it tapped the button once with the main thread idle, then started the sort as a task and tapped again about 100 ms later:
Output:
click on an idle main thread: input delay 2 ms (median of 5) click during the sort: arrived 106 ms into a 542 ms task, input delay 437 ms (medians of 5)
The numbers fit together: 106 ms plus 437 ms is 543 ms, within 1 ms of the end of the 542 ms task. The three values are separate medians, so they need not add up exactly, but the tap waited for about the part of the task that was left. During those 542 ms the browser also drew no frames, which at 60 Hz is about 32 frames in which the screen could not change.
Look at the orange bracket: the waiting time is set by the task, not by the button or the click code. Notice that the idle row and the busy row run the same handler, and only the state of the main thread differs.
What Shortens the Wait
The design choices fall into three groups, in the order to consider them.
- Do less work in the browser. Basket shows 30 products per page, so the server can sort the 4,000 and send 30 formatted prices. Formatting 30 prices instead of 4,000 is less than one percent of the work.
- Split the work. Work that must stay in the browser can run as several tasks under 50 ms each, so the loop can handle a tap between them.
- Move the work off the main thread. A Web Worker can sort a large list while the main thread keeps handling input, and then post the result back.
Measuring comes first in each case. The Long Tasks API and the browser's performance panel show which tasks are long and which code they ran.
Using This in an Interview
Say the rule and its number: "Any task over 50 ms delays input, so heavy work such as sorting the full catalog goes to the server or a worker, and the main thread only renders the 30 visible rows."
Two follow-up questions are likely:
- "Why does a promise callback run before a
setTimeoutcallback with a delay of zero?" - "How would you find which code is causing long tasks on real users' phones?"
Key Takeaways
- The main thread runs JavaScript, style, layout, paint and input handling one at a time, so any one of them can delay the others.
- Each turn of the event loop runs one task, then every waiting microtask, then a frame if one is due. Rendering never happens in the middle of a task.
- A long task holds the main thread for more than 50 ms. Sorting and formatting 4,000 prices took 70 ms at full speed, and 359 ms on one open page or 542 ms on fresh loads with the CPU slowed four times.
- Input delay is the wait before a handler starts. A tap during the 542 ms task waited 437 ms, against 2 ms on an idle thread.
- Shorten the wait by doing less work in the browser, splitting work into tasks under 50 ms, or moving it to a Web Worker.
The main thread also decides how soon a page built in the browser can appear at all. The next lesson, Client Rendering and Server Rendering, compares building Basket's product list in the browser with sending it as finished HTML.
Practice Questions
Try each question first, then open the answer.
1. A tap arrives 40 ms into a 250 ms task. About how long is the input delay, and what decides it?
<details> <summary>Show answer</summary>About 210 ms, decided by the part of the task that is left. The browser handles the tap as a new task, and it cannot start until the current task ends at 250 ms. In the lab, a tap 106 ms into a 542 ms task waited 437 ms, which matches the same arithmetic.
</details>2. Code inside a click handler runs await fetch(...) and then updates the cart count. Is the code after await a task or a microtask, and when does it run?
It runs as a microtask after the fetch promise settles. The handler's task ends at the await, so the main thread is free while the request is in flight. When the response arrives, the code after await runs as a microtask, before the next frame is drawn.
3. A function processes a queue by calling itself through Promise.resolve().then(...) thousands of times. Why does the page freeze even though each call is tiny?
The microtask step runs until its queue is empty, and each call adds another microtask. The loop never leaves the microtask step, so it never takes a rendering opportunity and never runs the next task, which includes input. Small steps help only when each one is a separate task.
</details>4. Basket's search page filters 4,000 products in the browser on every key press, and each filter takes 120 ms on a mid-range phone. Name two design changes and say which one you would try first.
<details> <summary>Show answer</summary>First, ask the server for the filtered page of 30 results; second, move the filter to a Web Worker. The server already holds the catalog, so the browser does almost no work and the main thread stays free. A worker keeps the full list in the browser but takes the 120 ms off the main thread, so typing stays responsive.
</details>5. Why is the long task limit 50 ms and not 16.7 ms, the length of one frame?
<details> <summary>Show answer</summary>The limit is about responding to input within about 100 ms, not about drawing every frame. If no task runs longer than 50 ms, any input waits at most 50 ms, which leaves about 50 ms for the handler and the next frame. Smooth animation needs shorter tasks than that, but a page can feel responsive with tasks under 50 ms.
</details>Reading Progress
0%
On This Page
One Thread for Most of the Page
The Event Loop
Long Tasks
Input Delay
What Shortens the Wait
Using This in an Interview
Key Takeaways
Practice Questions