4

Per the title, I am curious if every time I create an interval with setInterval if, because of the shimming done by Angular, if this creates a change detection event every time the interval runs.

I've been reading all the documentation I can find, but I can't find a clear answer on this.

for clarification, my question is, if I ran the following code, would every iteration of the interval trigger a change detection event and cause Angular to attempt to update the view of the application until the conditions are met?

let myInterval = setInterval( () => {

    if (conditionsAreMet()){
        clearInterval(myInterval);
    }
})
StephenRios
  • 2,192
  • 4
  • 26
  • 42
  • Every async event triggers change detection AFAIK. Also check: https://stackoverflow.com/a/40903120/5706293 and https://stackoverflow.com/a/43480931/5706293 – eko May 30 '17 at 16:15

1 Answers1

8

It depends on what zone this setInterval is used. If it's used inside NgZone, then yes, it will trigger change detection every time. If you run it outside angular zone, it won't trigger change detection.

Outside Angular zone:

export class AppComponent {
  name = 'Angular';

  constructor(zone: NgZone) {
    // will not trigger change detection
    zone.runOutsideAngular(() => {
      setInterval(() => {
        this.name = 'boob';
      }, 2000);
    })

Inside Angular zone:

export class AppComponent {
  name = 'Angular';

  constructor(zone: NgZone) {
    // will trigger change detection
    setInterval(() => {
      this.name = 'boob';
    }, 2000);
  }
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • So if it is inside a component being loaded by the Angular application, it will trigger change detection? – StephenRios May 30 '17 at 16:17
  • @StephenRios, it depends on how you use it. In my first example it's launched from inside the component, but outside Angular zone. But in general, yes, if you simply use `setInterval` inside a component's methods that are hooks or methods that react to events, it will schedule a change detection cycle – Max Koretskyi May 30 '17 at 16:22
  • I think the second example's "will not trigger" is a typo, and is supposed to be "will trigger". That's the whole point, right? (I was going to edit it myself but I want to be 100% sure I understand it first.) – Coderer Oct 02 '20 at 10:28