我需要在Javascript代码中添加大约100毫秒的延迟,但是我不想使用对象的setTimeout
功能,window
也不想使用繁忙的循环。有没有人有什么建议?
Answers:
不幸的是,这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 sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
其他的使用XMLHttpRequest
与服务器脚本捆绑在一起的脚本,在返回结果之前会休眠一段时间。
不幸的是,这些是变通办法,并且可能导致其他问题(例如冻结浏览器)。建议您坚持使用推荐的方法,即setTimeout()
)。
setTimeout()
。
1e7
价值?
如果您对ES2017没问题,那就await
很好:
const DEF_DELAY = 1000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}
await sleep(100);
请注意,该await
部分需要处于异步函数中:
//IIAFE (immediately invoked async function expression)
(async()=>{
//Do some stuff
await sleep(100);
//Do some more stuff
})()
我有一个问题需要适当解决。
通过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();
希望这可以帮助。
该线程进行了很好的讨论和有用的解决方案:
function pause( iMilliseconds )
{
var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}
不幸的是,这似乎在某些版本的IE中不起作用,但是如果证明这对您来说是一个问题,则该线程还有许多其他有价值的建议。
setTimeout
无法胜任的情况。但是+1为创造力。:)
使用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;
}