Coder Perfect

[duplicate] JavaScript sleep/wait before proceeding


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


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
    //do what you need here
}, 2000); is an example.

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

    console.log("THIS IS");
}, 2000);

This will be printed in the console:


(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){

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



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