Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of setTimeout in Angular?

Tags:

angular

Below is a snippet of code from the Tour of Heros tutorial for Angular.io:

getHeroesSlowly(): Promise<Hero[]> {
  return new Promise(resolve => {
     // Simulate server latency with 2 second delay
    setTimeout(() => resolve(this.getHeroes()), 2000);
  });
}

The description states: To simulate a slow connection, import the Hero symbol and add the following getHeroesSlowly() method to the HeroService.

I understand that it is best practice to build websites based on slow connections with two examples of such being here and here.

But why would I set a timer to test the build (like the one that Angular suggests) instead of throttling the connection (say in Chrome)?

like image 573
Liam Avatar asked Sep 15 '17 19:09

Liam


2 Answers

In your example the setTimeout is used to simulate server response in two seconds. It doesn't necessarily mean that it simulates slow connection. A response can come in two seconds for various reasons, one being that server takes 2 seconds to complete its job. However, as you noticed, this is not production code and is used to demonstrate a specific feature of the framework.

The most common use for setTimeout in production code is to allow Angular to run change detection once between actions that you would otherwise perform synchronously. In the article Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError error this method is suggested as a possible solution to the error.

like image 196
Max Koretskyi Avatar answered Oct 04 '22 01:10

Max Koretskyi


This is just a basic example of a slow connection with API, as you quoted, so you could see the loading data. Throttling the connection (in Chrome) as you said, would not simulate the delay of the connection between the API and the client, it would be slowing the whole web page.

More interesting would be using both tricks at the same time.

like image 27
Ap0st0l Avatar answered Oct 04 '22 01:10

Ap0st0l