View Full Version : setTimeout()

08-01-2011, 05:20 AM
Is there another JS function that I can use to force a time delay without having the code continue to run? I'm using the setTimeout() function but the call to this function doesn't stop the code flow. I need to stop the code flow while waiting. I guess I need a Sleep() type of JS function.

What I'm trying to do is display some blank text on the screen using a for loop (I'm using &nbsp;<BR> to give the appearance of "opening up" a vertical window section in the browser) and I need this 'text' to complete before allowing the following code in the function to execute. The following code will display a Table with rows of data. I'm trying to use a timing function to give a visual impression of a window opening up just before the data displays.


Philip M
08-01-2011, 07:34 AM
There is no sleep() method in Javascript. The following is a horrible work-around kludge which charges the CPU 100% and freezes all the other Javascripts on the page.

<input type = "text" name = "txt1" onblur = "snooze(5)">

<script type = "text/javascript">

function snooze(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");

alarm = new Date();
alarmMSeconds = alarm.getTime();
if (alarmMSeconds - startingMSeconds > naptime){sleeping = false}
alert ("Wake Up!");


A much better way is to use setTimeout() to create a delay:-

function doStuff() { //do some things or nothing
setTimeout(continueExecution, 10000) //wait ten seconds before continuing
function continueExecution() {
//finish doing things after the pause
Quizmaster: In the early fifteenth century Owain Glyndwr led a rebellion against the ruling English in which country?
Contestant: China.