JavaScript 中有睡眠/暂停/等待功能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7854820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Sleep/Pause/Wait function in JavaScript?
提问by Richard
Is there a JavaScript function that simulates the operation of the sleep
function in PHP?—?a function that pauses code execution for x milliseconds, and then resumes where it left off?
是否有一个 JavaScript 函数可以模拟sleep
PHP 中函数的操作?--暂停代码执行 x 毫秒,然后从停止的地方继续执行的函数?
I found some things here on Stack Overflow, but nothing useful.
我在 Stack Overflow 上找到了一些东西,但没有任何用处。
采纳答案by Diodeus - James MacFarlane
You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.
您需要将代码重新分解为多个部分。这不会停止执行,它只是在部件之间延迟。
function partA() {
...
window.setTimeout(partB,1000);
}
function partB() {
...
}
回答by Michael Haren
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
您不能(也不应该)使用睡眠功能阻止处理。但是,您可以使用setTimeout
在延迟后启动函数:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
根据您的需要,setInterval
也可能有用。