Vingtoft Vingtoft - 1 month ago 17
Javascript Question

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?

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

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