0

I have a component with some lifecycle hooks.

By synchronous I mean the execution of hooks one after another.

export class MyComponent implements OnInit, OnChanges, AfterContentInit, AfterViewInit {
  ngOnInit() {
    console.log('ngOnInit');
    setTimeout(() => {
        console.log('setTimeout');
    });
  } 

  ngOnChanges(changes: SimpleChanges): void {
    console.log('ngOnChanges');
  }

  ngAfterContentInit(): void {
    console.log('ngAfterContentInit');
  }

  ngAfterViewInit(): void {
    console.log('ngAfterViewInit');
  }
}

There are two cases

  1. They are Synchronous - Then setTimeout call at the end is justified by itself. But can someone please point me any Angular documentation or Angular code to support it.

  2. If not - Can anyone help me understand why setTimeout is running at the end.

I know how event loop works and that life cycle hooks run in sequence, but my question is how Angular achieves it? when I look at the call stack in chrome debugging mode, I don't find any sequence.

Is it guaranteed that setTimeout in the above example will run after all the above hooks?

prabhatojha
  • 1,925
  • 17
  • 30
  • please read , its a sequence : https://angular.io/guide/lifecycle-hooks#lifecycle-sequence – Joel Joseph Oct 14 '19 at 09:38
  • 2
    setTimeout is moved to the event loop. you should read how the thread reads from the event loop. check this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop – Jazib Oct 14 '19 at 09:40
  • @JoelJoseph, I know both the things, but I couldn't find any documentation where it says life cycle hooks are synchronous (though they run in a sequence). – prabhatojha Oct 14 '19 at 12:59
  • yes it is guaranteed that it will work after all the lifecycle hooks. because the thread finishes everything related to the view then goes looking in the event loop. so when the thread is completely done working with your view all your lifecycle hooks are complete, then it moves to the event loop – Jazib Oct 14 '19 at 17:32

0 Answers0