javascript / intermediate
Snippet
Optimizing with NgZone.runOutsideAngular
Angular tracks changes via Zone.js. For high-frequency events that don't need UI updates, running code outside the zone prevents unnecessary change detection cycles.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { Component, NgZone, OnInit, inject } from '@angular/core';@Component({ selector: 'app-perf', template: '' })export class PerfComponent implements OnInit {private zone = inject(NgZone);ngOnInit() {this.zone.runOutsideAngular(() => {setInterval(() => { /* Heavy side effect */ }, 50);});}}
angular
Breakdown
1
private zone = inject(NgZone);
Injects the NgZone service to interact with Angular's execution context.
2
this.zone.runOutsideAngular(() => {
Executes the callback without triggering Angular's change detection.
3
setInterval(() => { /* Heavy side effect */ }, 50);
Repeats a task frequently without slowing down the main UI thread via detection overhead.