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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:51:25  来源:igfitidea点击:

Is there a Sleep/Pause/Wait function in JavaScript?

javascriptsleep

提问by Richard

Is there a JavaScript function that simulates the operation of the sleepfunction in PHP?—?a function that pauses code execution for x milliseconds, and then resumes where it left off?

是否有一个 JavaScript 函数可以模拟sleepPHP 中函数的操作?--暂停代码执行 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 setTimeoutto kick off a function after a delay:

您不能(也不应该)使用睡眠功能阻止处理。但是,您可以使用setTimeout在延迟后启动函数:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setIntervalmight be useful, too.

根据您的需要,setInterval也可能有用。

回答by raphie

setTimeout() function it's use to delay a process in JavaScript.

setTimeout() 函数,它用于延迟 JavaScript 中的进程。

w3schoolshas an easy tutorial about this function.

w3schools有一个关于这个功能的简单教程。