把一个延迟在Javascript中

我需要添加约100毫秒的延迟到我的Javascript代码,但我不想使用window对象的setTimeout函数,我不想使用繁忙的循环。 有没有人有什么build议?

不幸的是, setTimeout()是唯一可靠的方法(不是唯一的方法,但唯一可靠的方法)暂停脚本的执行而不会阻塞UI。

实际上并不难,而不是写这个:

 var x = 1; // Place mysterious code that blocks the thread for 100 ms. x = x * 3 + 2; var y = x / 2; 

你使用setTimeout()来重写它:

 var x = 1; var y = null; // To keep under proper scope setTimeout(function() { x = x * 3 + 2; y = x / 2; }, 100); 

我明白,使用setTimeout()涉及更多的想法,而不是一个理想的sleep()函数,但不幸的是后者不存在。 有很多解决方法来尝试实现这些function。 有些使用繁忙循环:

 function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } 

其他人则使用XMLHttpRequest绑定一个服务器脚本,在返回结果之前hibernate一段时间 。

不幸的是,这些是解决方法,可能会导致其他问题(如冻结浏览器)。 推荐使用推荐的方法,即setTimeout() )。

我只是有一个问题,我需要正确解决这个问题。

通过Ajax,脚本获取X(0-10)消息。 我想做什么:每10秒向DOM添加一条消息。

代码我结束了:

 $.each(messages, function(idx, el){ window.setTimeout(function(){ doSomething(el); },Math.floor(idx+1)*10000); }); 

基本上,将超时视为脚本的“时间线”。

这是我们想要编码的:

 DoSomething(); WaitAndDoNothing(5000); DoSomethingOther(); WaitAndDoNothing(5000); DoEvenMore(); 

这是我们如何把它告诉JAVASCRIPT:

 At Runtime 0 : DoSomething(); At Runtime 5000 : DoSomethingOther(); At Runtime 10000: DoEvenMore(); 

希望这可以帮助。

实际上,只有setTimeout对于这个工作来说很好,通常你不能把非确定的方法设置为繁忙循环。

这个线程有一个很好的讨论和有用的解决scheme:

 function pause( iMilliseconds ) { var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');'; window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")'); } 

不幸的是,这在IE的某些版本中似乎不起作用,但是如果certificate对您有问题,则该线程还有许多其他有价值的build议。

使用一个AJAX函数,它将同步调用一个php页面,然后在该页面中,您可以将php usleep()函数作为一个延迟。

 function delay(t){ var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false); //This will call the page named delay.php and the response will be sent to a division with ID as "response" xmlhttp.send(); document.getElementById("response").innerHTML=xmlhttp.responseText; } 

http://www.hklabs.org/articles/put-delay-in-javascript