jQuery JavaScript 在继续之前休眠/等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16873323/
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-26 17:56:50  来源:igfitidea点击:

JavaScript sleep/wait before continuing

javascriptjquerydelaysleepwait

提问by user2370460

I have a JavaScript code that I need to add a sleep/wait function to. The code I am running is already in a function, eg:

我有一个 JavaScript 代码,需要向其中添加睡眠/等待功能。我正在运行的代码已经在一个函数中,例如:

function myFunction(time)
{
    alert('time starts now');
    //code to make the program wait before continuing
    alert('time is up')
}

I have heard that a possible solution might include

我听说一个可能的解决方案可能包括

setTimeout

but I am not sure how to use it in this case.

但我不确定在这种情况下如何使用它。

I can't use PHP, as my server does not support it, although using jQuery would be fine.

我不能使用 PHP,因为我的服务器不支持它,尽管使用 jQuery 会很好。

回答by BeNdErR

JS does not have a sleep function, it has setTimeout()or setInterval()functions.

JS 没有睡眠函数,它有setTimeout()setInterval()函数。

If you can move the code that you need to run after the pause into the setTimeout()callback, you can do something like this:

如果您可以将暂停后需要运行的代码移动到setTimeout()回调中,您可以执行以下操作:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

请参阅此处的示例:http: //jsfiddle.net/9LZQp/

This won't halt the execution of your script, but as long as setTimeout()is an asynchronous function, this code

这不会停止脚本的执行,但只要setTimeout()是异步函数,此代码

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

将在控制台中打印:

HELLO
DOG
THIS IS

(note that DOGis printed before THIS IS)

(注意DOG打印在THIS IS之前)



You can use the following code to simulate a sleep for short periods of time:

您可以使用以下代码来模拟短时间的睡眠:

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

now, if you want to sleep for 1 second, just use:

现在,如果你想睡一秒钟,只需使用:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

示例:http: //jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

请注意,此代码将使您的脚本忙碌n 毫秒。这不仅会停止在您的页面上执行 Javascript,而且根据浏览器的实现,可能会使页面完全无响应,并可能使整个浏览器无响应。换句话说,这几乎总是错误的做法。