All,
I searched all around looking for a way to do an actual sleep function (Thread.Sleep, wait, sleep(), take your pick...) in JavaScript, and there were many posts around that use setInterval or setTimeout, there were none that actually did a real sleep.
The problem is, the setTimeout function immediately returns control to its container after it sets the timer. So, if you setTimeout(funct(),1000), and its container runs for 5 seconds longer, the last 4 seconds will see BOTH functions running at the same time. Now, arguably, this is good in some cases, perhaps even most cases as it relates to JavaScript applications. However, in an application I've been working on recently, I needed to actually sleep for a couple seconds. Literally make the script stall. The reason is, I'm using AJAX to retrieve some data, but its a very fast pull, taking almost no time at all, but we WANT the user to see the processing animation for a couple seconds (for psycological affect... its a sort of quiz).
So, here's what I did. Its actually pretty obviouls in hindsight, so I'm surprised I didn't find any one else using this technique. This is actually an except from a larger class file... Anyway, this is mostly for posterity, but comments are welcome. Oh, and I'm sure there are good reasons for not normally wanting to do this, also, I suppose if you ran this for too long, browsers would throw errors or crash... I only need it for 3-5 seconds, so this isn't a problem for me.
this.Sleep = function ZZzzzZZzzzzzzZZZz(naptime){
naptime = naptime * 1000;
var sleeping = true;
var now = new Date();
var alarm;
var startingMSeconds = now.getTime();
alert("starting nap at timestamp: " + startingMSeconds + "\nWill sleep for: " + naptime + " ms");
while(sleeping){
alarm = new Date();
alarmMSeconds = alarm.getTime();
if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
}
alert("Wakeup!");
}
- this.Sleep = function ZZzzzZZzzzzzzZZZz(naptime){
- naptime = naptime * 1000;
- var sleeping = true;
- var now = new Date();
- var alarm;
- var startingMSeconds = now.getTime();
- alert("starting nap at timestamp: " + startingMSeconds + "\nWill sleep for: " + naptime + " ms");
- while(sleeping){
- alarm = new Date();
- alarmMSeconds = alarm.getTime();
- if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
- }
- alert("Wakeup!");
- }
This is part of a class function, and since I also set var my = this; right at the top of any JS class I write, this would be called privately as my.Sleep(5), and publicly like myObject.Sleep(5) (assuming you named the object myObject, which you probably wouldn't

)
.c