在 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 中调用的函数中…

有没有办法解决?

原文由 Nathan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 324
2 个回答

代码是否包含在函数中?

 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

}

原文由 David Hedlund 发布,翻译遵循 CC BY-SA 2.5 许可协议

上周我遇到了需要类似功能的情况,这让我想到了这篇文章。基本上我认为@AndreKR 所指的“忙等待”在很多情况下都是合适的解决方案。下面是我用来占用浏览器并强制等待的代码。

 function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

document.write("first statement");
alert("first statement");

pause(3000);

document.write("<br />3 seconds");
alert("paused for 3 seconds");

请记住,此代码实际上会占用您的浏览器。希望它能帮助任何人。

原文由 Nathan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题