JavaScript sleep/wait before continuing [duplicate

2019-01-02 16:54发布

This question already has an answer here:

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条回答
伤终究还是伤i
2楼-- · 2019-01-02 17:13

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.

查看更多
登录 后发表回答