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

有没有办法解决?

代码是否包含在一个函数中?

 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 } 

上周我遇到了需要类似function的情况,这让我想起了这篇文章。 基本上我认为@AndreKR提到的“忙碌的等待”在很多情况下都是合适的解决scheme。 下面是我用来浏览器的强制等待条件的代码。

 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"); 

只要把它放在callback里面:

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

不,因为Javascript中没有延迟function,除了忙于等待(这会locking浏览器)之外,没有办法做到这一点。

 setTimeout(function() { yourCode(); // alert('this alert is timedout and should be the first'); otherCode(); // alert("this should be the second one"); }, 5000); 

你可以尝试用你自己的函数replacewindow.setTimeout,像这样

 window.setTimeout = function(func, timeout) { func(); } 

这可能会或可能不会正常工作。 除此之外,你唯一的select是改变原来的代码(你说你不能这样做)

请记住,像这样改变本地function并不是一个非常理想的方法。