JavaScript在继续之前休眠/等待 [英] JavaScript sleep/wait before continuing

查看:171
本文介绍了JavaScript在继续之前休眠/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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.

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

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

推荐答案

JS确实如此没有睡眠功能,它有 setTimeout() setInterval() 功能。

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

如果您可以将暂停后需要运行的代码移动到 setTimeout()回调中,可以做这样的事情:

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

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

参见此处示例: http://jsfiddle.net/9LZQp/

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

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

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

将在控制台中打印出来:

will print this in the console:

HELLO
DOG
THIS IS

(请注意 DOG 这是之前打印)

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

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;
    }
  }
}

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

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

sleep(1000);

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

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

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.

这篇关于JavaScript在继续之前休眠/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆