Liam
Liam

Reputation: 281

What is the purpose of setTimeout in 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)?

Upvotes: 7

Views: 17301

Answers (3)

Max Koretskyi
Max Koretskyi

Reputation: 105517

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.

Upvotes: 8

Ap0st0l
Ap0st0l

Reputation: 616

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.

Upvotes: 3

bgraham
bgraham

Reputation: 2027

I think the point of this is because its not actually hitting a server. I think the getHeros method is just returning hardcoded data. They are trying to demonstrate how you would use Promises Angular style and having it wait a couple seconds before returning helps you understand how to deal with the state before you actually have the data. ie. checking to make sure lists are populated before you iterate over them.

Upvotes: 2

Related Questions