Vingtoft
Vingtoft

Reputation: 14606

Angular2: setTimeout only called once

I'm implementing functionality in Angular2 that requires the use of setTimeout.

My code:

  public ngAfterViewInit(): void {
    this.authenticate_loop();
  }

  private authenticate_loop() {
    setTimeout (() => {
      console.log("Hello from setTimeout");
    }, 500)
  }

setTimeout is started by ngAfterViewInit but the loop is only executed once, eg. "Hello fromsetTimeout" is only printed once.

Question: How can I change the code to make the setTimeout work?

Upvotes: 6

Views: 27071

Answers (2)

Tobi
Tobi

Reputation: 524

Edit: So to be more specific for the different angular versions:

In Angular2 you are not required to use $timeout / $interval any more. So for the question here setInterval is the correct solution.

For any one interested in the original response (targeted to Angular1) read the following:

Use $interval inside an angular.js application.

And if you want to use setTimeout somewhere else inside an angular.js application you should better use the $timeout service.

$timeout and $interval have the advantage, that they keep your scope updated, which setTimeout / setInterval do not.

Upvotes: 3

dlcardozo
dlcardozo

Reputation: 4013

 private authenticate_loop() {
    setInterval (() => {
      console.log("Hello from setInterval");
    }, 500)
 }

setTimeout will run just one time, unless you create another setTimeout.

Upvotes: 11

Related Questions