Angular 4 setTimeout不等待 [英] Angular 4 setTimeout does not wait

查看:313
本文介绍了Angular 4 setTimeout不等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用打字稿创建一个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?

推荐答案

由于您使用的是Angular,因此您可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆