Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 setTimeout does not wait

Tags:

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?

like image 785
fangio Avatar asked Jul 12 '17 12:07

fangio


1 Answers

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
    })
like image 187
Saravana Avatar answered Sep 28 '22 08:09

Saravana