Angular 4 setTimeout does not wait

fangio picture fangio · Jul 12, 2017 · Viewed 67.9k times · Source

I am creating an angular 4 app with typescript.

I'm having a function that needs to be executed every 10 seconds untill a specified stopcondition. I created a loop with some testcode using setTimeout to see if it would work.

My Testcode:

public run() {
    let i = 0;
    while (i < 4) {
        setTimeout(this.timer,3000);
        i++;
    }
}

public timer(){
    console.log("done")
}

However this seems to wait for 3 seconds, or browser is just slow... and then it prints 4 times done. So the code isn't working. Am I doing this wrong or are there other possibilities to do this kind of things?

Answer

Saravana picture Saravana · Jul 12, 2017

Since you are using Angular you can probably do this in a much simpler way using takeWhile:

Observable.interval(10000)
    .takeWhile(() => !stopCondition)
    .subscribe(i => { 
        // This will be called every 10 seconds until `stopCondition` flag is set to true
    })