6

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?

4
  • 1
    Because timeout only runs once... Commented Nov 3, 2016 at 13:30
  • you can see blog.neilni.com/2016/03/27/settimeout-in-angular-2 Commented Nov 3, 2016 at 13:31
  • Edit your question to angular 1 instead of angular 2, you have accepted an answer that uses angular 1 services. Commented Nov 3, 2016 at 13:45
  • True, did not notice. Correct answer has now been accepted. Commented Nov 3, 2016 at 13:46

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

Your answer is correct, but the examples used are angular1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.