Thursday, 27 August 2015

Sleep() in JavaScript

"What do I do if I need a Sleep() function in JavaScript?"
I have a JavaScript code that I need to add a sleep() 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')
Well, JS does not have a sleep function, it has setTimeout() or setInterval() functions.
The code would be:
var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);
The delay is given in miliseconds (see or

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 ME is printed before THIS IS)
function sleep(ms) {
    ms += new Date().getTime();
    while (new Date() < ms) { }
now, if you want to sleep for 3 seconds, 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.
If you do sleep more than 10 seconds, browser shows alert: "A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue."

1 comment: