在 JavaScript 中同步使用 setTimeout

2024-03-30

我有以下场景:

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

我需要后面的代码setTimeout执行完setTimeout中的代码后执行。由于后面的代码setTimeout不是我自己的代码我不能将它放在 setTimeout 中调用的函数中...

有没有办法解决?


代码是否包含在函数中?

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

    // code that you cannot modify?
}

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

function test(flag) {

    if(!flag) {

        setTimeout(function() {

           alert();
           test(true);

        }, 5000);

        return;

    }

    // code that you cannot modify

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 JavaScript 中同步使用 setTimeout 的相关文章

随机推荐