JavaScript sleep/wait before continuing [duplicate]

JavaScript sleep/wait before continuing [duplicate]

This question already has an answer here:

What is the JavaScript version of sleep()?

74 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

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.


Solution 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
    //do what you need here
}, 2000);

see example here :

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

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

will print this in the console:


(note that DOG is printed before THIS IS)

Related:  How to call outer function's return from inner function?

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

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



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.