Angular 4 setTimeout不等待 [英] Angular 4 setTimeout does not wait
问题描述
我正在使用打字稿创建一个angular 4应用程序.
I am creating an angular 4 app with typescript.
我有一个功能,需要每10秒执行一次,直到达到指定的停止条件为止.我使用setTimeout创建了一个带有一些测试代码的循环,以查看它是否有效.
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.
我的测试代码:
public run() {
let i = 0;
while (i < 4) {
setTimeout(this.timer,3000);
i++;
}
}
public timer(){
console.log("done")
}
但是,这似乎要等待3秒钟,否则浏览器就会变慢... 然后将其打印4次.因此代码无法正常工作.我做错了吗?还是有其他可能性做这种事情?
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
})
这篇关于Angular 4 setTimeout不等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!