Coder Perfect

[duplicate] JavaScript sleep/wait before proceeding

Problem

Toss in a sleep/wait function. The code I’m running is already contained within a function, for example:

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

According to what I’ve heard, a viable remedy could involve

setTimeout

However, I’m not sure how to apply it in this situation.

I can’t use PHP because my server doesn’t support it, but jQuery will suffice.

Asked by user2370460

Solution #1

There is no sleep function in JS; instead, it has setTimeout() and setInterval() functions.

You can do something like this if you can relocate the code that needs to run after the pause inside the setTimeout() callback:

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

http://jsfiddle.net/9LZQp/ is an example.

This won’t stop your script from running, but because setTimeout() is an asynchronous method, this code will.

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

This will be printed in the console:

HELLO
DOG
THIS IS

(Note that DOG comes first, followed by THIS IS)

To simulate sleep for short periods of time, use the following code:

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

If you wish to sleep for one second, simply type:

sleep(1000);

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

This code will keep your script busy for n milliseconds, so keep that in mind. This will not only stop the execution of Javascript on your page, but it may also render the page unresponsive, and perhaps the entire browser unresponsive, depending on the browser implementation. To put it another way, this is usually always a bad idea.

Answered by BeNdErR

Post is based on https://stackoverflow.com/questions/16873323/javascript-sleep-wait-before-continuing