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 developer.mozilla.org/en-US/docs/Web/API/window.setTimeout or http://www.w3schools.com/js/js_timing.asp).

See example here: http://jsfiddle.net/forgery/02u8uwg1/

This won't halt the execution of your script, but as long as setTimeout() is an asynchronous function, this code
 
console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("ME");
will print this in the console:
 
HELLO
ME
THIS IS
*(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:
 
sleep(3000);
example: http://jsfiddle.net/forgery/8t0neran/

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."