在Javascript中加入延迟 [英] Put a Delay in Javascript
问题描述
我需要为我的Javascript代码添加大约100毫秒的延迟,但我不想使用窗口的
对象,我不想使用繁忙的循环。有没有人有任何建议? setTimeout
函数
I need to add a delay of about 100 miliseconds to my Javascript code but I don't want to use the setTimeout
function of the window
object and I don't want to use a busy loop. Does anyone have any suggestions?
推荐答案
不幸的是, setTimeout()
是唯一的可靠方式(不是唯一的方法,但唯一的可靠方式)暂停脚本的执行而不会阻止UI。
Unfortunately, setTimeout()
is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI.
实际使用并不难,而不是写这个:
It's not that hard to use actually, instead of writing this:
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()
函数还要多,但遗憾的是后者不存在。有许多变通方法可以尝试实现这些功能。一些使用繁忙循环:
I understand that using setTimeout()
involves more thought than a desirable sleep()
function, but unfortunately the later doesn't exist. Many workarounds are there to try to implement such functions. Some using busy loops:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
其他使用与服务器绑定的 XMLHttpRequest
在返回结果之前会休眠一段时间的脚本。
others using an XMLHttpRequest
tied with a server script that sleeps for a amount of time before returning a result.
不幸的是,这些是解决方法,可能会导致其他问题(例如冻结浏览器) 。建议只使用推荐的方式,即 setTimeout()
)。
Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers). It is recommended to simply stick with the recommended way, which is setTimeout()
).
这篇关于在Javascript中加入延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!