Sub topic 6
Spotting long tasks that block the main thread
This chapter assumes you can record a trace in the Performance panel and find the Main track in the flame chart. It also assumes you know the browser event loop well enough to say that a task runs to completion before the next one starts. Here you learn how to find the tasks that make an Angular app feel frozen, and how to tell what they cost.
What a long task is
The browser's main thread runs JavaScript, style calculation, layout, and painting. It also handles user input. It does one task at a time, and a task cannot be interrupted once it starts. A long task is any task that occupies the main thread for more than 50 milliseconds.
The 50 ms threshold comes from a response budget. If input is handled within about 100 ms, users perceive the app as instant. The browser needs some of that time for its own work, so a task longer than 50 ms risks pushing the response past the budget.
While a long task runs, nothing else can happen on that thread:
- Clicks and key presses wait in the queue.
- CSS animations driven by the main thread stall.
- Angular cannot render updates, because rendering is also main-thread work.
The following diagram shows how one long task delays a click.
The user clicked at 40 ms and saw a response after 180 ms. The click handler itself may be fast. The delay comes from the task that was already running.
Finding long tasks in a trace
Record a trace of the interaction that feels slow. Then look at the Main track in the Performance panel.
DevTools marks long tasks in two ways:
- A red triangle appears in the top-right corner of the task bar.
- The part of the task beyond 50 ms is filled with red diagonal stripes.
The striped portion is the useful part. A 70 ms task has 20 ms of stripes, and a 400 ms task has 350 ms. The stripes show how much time counts against responsiveness.
Follow this routine when you open a trace:
- Zoom the overview to the time range of the interaction, by dragging across it.
- Scan the Main track for red triangles.
- Click the widest striped task. The Summary tab shows its duration, and the Bottom-Up tab shows where self time went.
- Expand the task in the flame chart and follow the widest bar downward until you reach a single wide function with little beneath it. That function is usually where the time was spent.
Remember that the flame chart shows a call stack that grows downward. A wide bar near the top that has only thin children means the time is spread over many small calls. A wide bar with a single wide child means one function owns the time.
What kind of work fills the task
The color of the bars tells you the category:
| Color | Category | Typical cause in an Angular app |
|---|---|---|
| Yellow | Scripting | Event handlers, change detection, your own loops |
| Purple | Rendering | Style recalculation and layout |
| Green | Painting | Painting and compositing |
A long task that is mostly yellow points to JavaScript. A long task with a large purple section often means layout was forced or too many DOM nodes changed. The two cases have different fixes, so check the color before you change code.
Typical sources in Angular apps
Long tasks in Angular apps tend to come from a small set of causes:
- Heavy synchronous work in an event handler, such as sorting or filtering a large array.
- Bootstrap and first render, where a lot of component creation happens in one task.
- A large change detection pass that checks many bindings, covered in later chapters.
- A big DOM update, such as rendering thousands of list rows at once.
You will often see the task begin with a browser event such as click, then Function Call, and then Zone.js frames wrapping the Angular work. The next chapter explains why those Zone.js frames appear.
Measuring long tasks from code
A trace shows one recording on your machine. You can also detect long tasks in code, which helps in automated tests or when you collect data from other devices. The PerformanceObserver interface reports them in Chromium-based browsers.
const observer = new PerformanceObserver(list => {
for (const entry of list.getEntries()) {
console.warn(
`Long task: ${Math.round(entry.duration)} ms, started at ${Math.round(entry.startTime)} ms`
);
}
});
observer.observe({ type: 'longtask', buffered: true });The buffered: true option includes long tasks that happened before the observer was created, such as during startup. Put this snippet early in main.ts if you want to see startup tasks.
The Long Tasks API does not tell you which function was responsible. Use it to learn that a problem exists, then use a trace to learn the cause.
Breaking up a long task
Once you find the function that owns the time, you have two options. You can make the work cheaper, or you can split it so the browser can handle other tasks between pieces. Splitting does not reduce total work. It reduces the longest single block, so input and rendering can run in between.
This example processes 200,000 numbers in chunks and yields to the main thread after each chunk.
import { Component, signal } from '@angular/core';
function yieldToMain(): Promise<void> {
return new Promise(resolve => setTimeout(resolve, 0));
}
@Component({
selector: 'app-report',
template: `
<button (click)="build()">Build report</button>
<p>Processed: {{ processed() }}</p>
`,
})
export class ReportComponent {
processed = signal(0);
async build() {
const data = Array.from({ length: 200_000 }, (_, i) => i);
const chunkSize = 10_000;
let sum = 0;
for (let start = 0; start < data.length; start += chunkSize) {
for (const value of data.slice(start, start + chunkSize)) {
sum += Math.sqrt(value);
}
this.processed.set(Math.min(start + chunkSize, data.length));
await yieldToMain();
}
console.log('Sum:', sum);
}
}In a trace, the single wide task becomes a row of short ones, each with a small gap. Click events that arrive during the work now run in a gap instead of waiting for the end.
Chrome also provides scheduler.yield(), which resumes your work ahead of other queued tasks. It is not available in every browser, so setTimeout is the portable choice shown here.
Edge cases and common mistakes
- Profiling a development build. Development mode adds extra checks, so tasks look longer than they will in production. Profile a production-like build, as covered earlier.
- Judging by one recording. Timings vary between runs. Record the interaction at least three times and compare the long tasks across them.
- Missing the CPU effect. A 40 ms task on a fast laptop can be 160 ms on a mid-range phone. Use CPU throttling to see what slower devices experience.
- Chasing short tasks. A 55 ms task has 5 ms of overshoot. Start with the widest striped tasks, since they have the largest effect.
- Ignoring a gap between tasks. Several 45 ms tasks in a row with no gaps block input almost as much as one long task. The browser may not get a chance to run input between them. Look at the idle gaps, not only at the red triangles.
- Confusing waiting with working. A long network request does not block the main thread. The Main track shows only the thread's own activity, so a wide empty area is idle time, not a long task.
Exercise
In a trace you see a task 130 ms long, marked with a red triangle. How many milliseconds are striped red, and why does the user still notice a delay if the click handler inside it takes only 5 ms?
Show answer
The striped portion is 80 ms, which is the 130 ms duration minus the 50 ms threshold. The user notices a delay because a click that arrives while the task is running waits in the queue until the whole task finishes. The handler's 5 ms runs only after that wait, so the response time includes the remaining time of the long task.
Exercise
You split a 300 ms loop into 30 chunks of about 10 ms with setTimeout between them. Total CPU work stays roughly the same. What improves, and what should you check in the new trace?
Show answer
The longest single task drops from about 300 ms to about 10 ms, so clicks and rendering can run between the chunks and the app stays responsive. In the new trace, check that no task has a red triangle, that the gaps between chunks are present, and that change detection triggered after each timer callback does not add its own long task.