This question already has an answer here:
- What is the JavaScript version of sleep()? 69 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.
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: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 codewill print this in the console:
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
now, if you want to sleep for 1 second, just use:
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.