Enn
Enn

Reputation: 2209

Why does setTimeout in Angular & dramatically increase runtime performance?

This is gonna sound a bit abstract, but I'm really curious as to what might be possible cause of this behavior.

Setup:

Angular 9.1.0
All components use OnPush detection strategy

I have component (quite UI heavy with flex layout) which is initialized in *ngFor about 10 times on a page. This component has single number Input property from which it generates layout.

When I use:

ngOnChanges(changes: SimpleChanges) {
   if (this.id) {
      this.initComponent(this.id); // this triggers component to be rendered
   }
}

it takes about 5-7 seconds to render.

If I use:

ngOnChanges(changes: SimpleChanges) {
   if (this.itemId) {
          setTimeout(() => {
           this.initComponent(this.itemId ?? 0);
    }, 1);
  }
}

it takes under 1 second to render everything. I'm looking for ideas of what might be causing such behavior so that I can improve my code or understand the flaw in my current code.

Upvotes: 0

Views: 641

Answers (1)

CodeWarrior
CodeWarrior

Reputation: 5176

Angular runs as a single thread application. So when you try to render the UI it has to wait for the Javascript engine to finish its processing to be rendered.

setTimeout() is scheduled in native code. So essentially what happens is that the Javascript engine exits to native code, native code (setTimeout()) renders the UI and then exits to go back to the Javascript engine where it can continue processing.

Hence, putting your UI code in setTimeout() produces that result.

Upvotes: 2

Related Questions