JavaScript sleep/wait before continuing [duplicate]

我与影子孤独终老i 提交于 2019-11-26 01:11:29

问题


This question already has an answer here:

  • What is the JavaScript version of sleep()? 75 answers

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.

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


回答1:


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

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

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

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

(note that DOG is printed before 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/

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.



来源:https://stackoverflow.com/questions/16873323/javascript-sleep-wait-before-continuing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!