Sleeping with Javascript
When I went looking for a built-in “sleep()” function in Javascript, I quickly learned that it does not exist. This is surprising considering that “sleep()” is in all other languages that I have used. To get around this javascript shortcoming, I decided to create my own sleep function. The result is a function that loops internally until the number of seconds passed is greater than the argument value, “naptime”.
Initial tests of “sleep()” were successful, however, I soon discovered that most browsers will interrupt “sleep()” and show a “Slow/Busy script” dialog message whenever the “naptime” argument is greater than 10 seconds (7 seconds in IE). Trying to work around this problem was too much effort, so I left the script as is. If you use this function, I recommend a “naptime” of less than 10 seconds so your site visitors won’t encounter this “slow script” dialog message.
Below are some examples of the javascript “sleep()” function. Just click on a link below to start sleeping for the preset amount of seconds shown.
[Sleep for 3 Seconds] [Sleep for 5 Seconds] [Sleep for 10 Seconds] [Sleep for 20 Seconds]
Here is the script source:
//A javascript sleep function by Helene D.
jQuery.fn.sleep = function (naptime) {
var loop = false;
var maxiterations = 9000000;
var now = new Date();
var timestarted = now.getTime();
naptime=naptime+0; //convert to number
if (naptime >0 ) {
loop = true;
if (naptime < 100) { //convert to microseconds
naptime=(naptime*1000);
naptime=naptime-940; //estim. script exec time
}
}
var i=0;
while(loop) {
i++;
now = new Date();
timenow = now.getTime();
if(timenow - timestarted > naptime) {
loop = false;
} else if (i > maxiterations) { //no infinite loops
loop = false;
}
}
return $(this);
}
The usage is: sleep(seconds);. You can also chain it in jQuery like this: $(this).sleep(seconds).replace(wakeUp);
If you are not a jQuery user, you can convert this function to plain javascript by replacing jQuery.fn.sleep = function(naptime)function sleep(naptime)return $(this)

