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?
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With