Sub topic 7
How Zone.js triggers Angular work
This chapter assumes you can run an Angular app with the CLI, read basic TypeScript, and know how the browser event loop schedules tasks and microtasks. You should also know how to open the Performance panel and record a trace. The goal is a working model of how Angular learns that "something may have changed", so that the activity you see in a trace makes sense.
The problem Zone.js solves
Angular must update the DOM when your data changes. A plain setTimeout callback, a click handler, or a resolved promise can all change component fields. Angular does not watch those fields directly. It needs a signal that says "some asynchronous work just finished, check the views now".
Zone.js provides that signal. It is a library that patches browser asynchronous APIs when the page loads. Patched APIs include these:
setTimeoutandsetIntervalPromise(thethencallbacks)addEventListenerand the event handlers it registersXMLHttpRequest,requestAnimationFrame, and similar APIs
A zone is an execution context that persists across asynchronous calls. Code that starts inside a zone keeps running in that zone, even inside a callback that fires later. Angular creates a zone called the Angular zone, exposed as NgZone. It runs your application code inside it.
The notification loop
When a task running in the Angular zone finishes, NgZone emits an event named onMicrotaskEmpty. Angular listens for it and runs change detection. Change detection is the pass that compares template bindings with their previous values and updates the DOM where they differ.
Two consequences matter for profiling:
- Change detection runs after the callback, not during it. In a trace, your handler appears first, and the change detection work follows in the same task or right after it.
- Angular does not check whether anything actually changed before it starts. Zone.js only reports that asynchronous work finished. The cost of the pass depends on how many components and bindings Angular has to check.
Seeing zone activity in a trace
Zone.js leaves recognizable names in the flame chart. Open a recording and look at the call stacks under a task such as an event or a timer. You will often see frames like these:
| Frame name | What it means |
|---|---|
| `ZoneDelegate.invokeTask` | Zone.js is running a scheduled task inside a zone |
| `Zone.runTask` | The zone is executing a callback that was scheduled earlier |
| `ZoneTask.invokeTask` | The wrapper that calls your callback |
| `NgZone.onEnter` / `onLeave` | Angular entering and leaving the zone around your code |
| `ApplicationRef.tick` | A full change detection pass starting from the root |
These frames are wrappers. Their self time is small. The time you care about is in the children: your handler, and the change detection frames after it. If a click task is 80 ms long, expand it and check whether the time is in your callback or in ApplicationRef.tick. That tells you whether the fix is in your logic or in how much Angular checks.
Zone.js also makes stack traces longer. Because every callback goes through zone wrappers, call stacks have several extra frames, and async stack traces in DevTools can combine frames from different zone tasks. Do not read those frames as your own code.
Why one timer can cost a lot
A common surprise is that one repeating timer triggers change detection for the whole application. Consider a component that polls every 100 ms:
import { Component, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-poller',
template: `<p>Last checked: {{ lastChecked }}</p>`,
})
export class PollerComponent implements OnInit, OnDestroy {
lastChecked = '';
private timerId: ReturnType<typeof setInterval> | undefined;
ngOnInit() {
this.timerId = setInterval(() => {
this.lastChecked = new Date().toISOString();
}, 100);
}
ngOnDestroy() {
clearInterval(this.timerId);
}
}This is correct code, and the view updates as expected. But the interval is patched by Zone.js, so each tick of the timer ends with onMicrotaskEmpty and a change detection pass over the component tree. That is ten passes per second, even if the rest of the page is idle. In the Performance panel you would see a small task every 100 ms, each containing ApplicationRef.tick.
Not every timer is a problem. If the page has few components and the passes take well under a millisecond, you can ignore this. It becomes a problem when the tree is large, or when many unrelated timers, sockets, or animation callbacks each trigger their own pass.
Taking work out of the zone
NgZone.runOutsideAngular runs a function in the parent zone, so tasks it schedules do not trigger change detection. Use it for work that does not need to update the view, such as scroll or mousemove listeners that only record data or draw to a canvas. The topic's full example appears in the outside-zone chapter, so this is a short version:
import { Injectable, NgZone, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class HeartbeatService {
private zone = inject(NgZone);
private id: ReturnType<typeof setInterval> | undefined;
start(send: () => void) {
this.zone.runOutsideAngular(() => {
this.id = setInterval(send, 1000);
});
}
stop() {
clearInterval(this.id);
}
}If the callback does need to update the UI, re-enter the zone for that one update with this.zone.run(() => { ... }). This keeps the frequent, cheap work outside the zone and triggers change detection only when the view must change.
Common errors and gotchas
- Assuming a slow task is your code. Zone wrapper frames are thin. Check the children before you blame or exonerate a handler.
- Third-party libraries that use timers or listeners. Charts, maps, and drag-and-drop libraries often register high-frequency events. If they were initialized inside the Angular zone, every event triggers a pass. Initialize them inside
runOutsideAngular. - Forgetting to clean up. A listener or interval registered outside the zone is not removed by Angular. Remove it in
ngOnDestroy, as the earlier examples do. - Zone-less Angular. Recent Angular versions support running without Zone.js, and then change detection is scheduled by signals,
markForCheck, and other notifications. In such an app you will not see zone frames in a trace. Check your app'smain.tsandangular.jsonpolyfills to find out which mode it uses. The rest of this chapter's guidance applies to apps that include Zone.js. - Zone.js and native
async/await. Zone.js cannot patch nativeasync/awaitdirectly, so Angular's build downlevelsasyncfunctions to promises for zone-based apps. If you see unexpected build output differences, this is the reason.
What to look for next
When you read a trace, ask three questions about each repeating task:
- What started it: a click, a timer, a network response, or an animation frame?
- How much of its time is your callback, and how much is
ApplicationRef.tick? - Does the work need to update the view at all?
The next chapter takes the second question further and shows how to recognize change detection itself in the flame chart.
Exercise
A page has a setInterval that runs every 50 ms and only writes a value to a canvas. The Performance panel shows a short task every 50 ms, and each one contains ApplicationRef.tick. What is the cause, and how would you change the code?
Show answer
The interval is registered inside the Angular zone, so Zone.js reports each callback as finished work and NgZone triggers a change detection pass every time. Register the interval inside NgZone.runOutsideAngular(...) so it does not trigger passes, and clear it in ngOnDestroy. Because the callback only draws to a canvas and does not update a template binding, nothing needs zone.run. After the change, record a new trace and confirm the ApplicationRef.tick frames no longer appear every 50 ms.
Exercise
After moving a scroll listener into runOutsideAngular, a counter in the template that shows the scroll position stops updating. Why, and what is the smallest fix?
Show answer
The listener now runs outside the Angular zone, so changing the field does not notify Angular and no change detection pass runs. The smallest fix is to call this.zone.run(() => { this.position = value; }) only when the displayed value must change, for example once per animation frame or when the value crosses a threshold. This keeps most scroll events outside the zone.