在JavaScript中同步使用setTimeout [英] using setTimeout synchronously in JavaScript

查看:69
本文介绍了在JavaScript中同步使用setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

setTimeout("alert('this alert is timedout and should be the first');", 5000);
alert("this should be the second one");

在setTimeout中的代码执行后,我需要在setTimeout之后的代码执行.由于setTimeout之后的代码不是我自己的代码,因此无法将其放在setTimeout中调用的函数中.

I need the code after the setTimeout to be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeout is not code of my own I can't put it in the function called in the setTimeout...

有什么办法解决这个问题吗?

Is there any way around this?

推荐答案

函数中包含代码吗?

function test() {
    setTimeout(...);     

    // code that you cannot modify?
}

在这种情况下,您可以阻止该函数进一步执行,然后再次运行它:

In that case, you could prevent the function from further execution, and then run it again:

function test(flag) {

    if(!flag) {

        setTimeout(function() {

           alert();
           test(true);

        }, 5000);

        return;

    }

    // code that you cannot modify

}

这篇关于在JavaScript中同步使用setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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