Geekpedia Programming Tutorials






Geekpedia / Programming FAQ / JavaScript / How do I make a JavaScript function wait before executing (sleep / delay)?

How do I make a JavaScript function wait before executing (sleep / delay)?



You'll need to enclose the code that you want to execute after the delay in a function (Func1()). This function will then be called with a delay, in our case from another function (Func1Delay()).

<script type="text/javascript">
function Func1()
{
alert("Delayed 3 seconds");
}

function Func1Delay()
{
setTimeout("Func1()", 3000);
}

</script>


Then you simply call Func1Delay() which in turn calls Func1() but with a delay of 3000 milliseconds (3 seconds):

<body onload="Func1Delay()">
</body>

See this code in action See this code in action


by Andrew Pociu at Sep, 21 2005 - 06:13 | 52126 hits

HSIM - Nov 24 2005 - 03:45

Wait there,

It does not work in a more complex situations where you need to run several commands in sequence. setTimeout() will immediately return and execution continues right away, after the call to Func1Delay function. Only Func1 will execute 3 seconds later.


Andrei Pociu - Nov 24 2005 - 04:53

Indeed, that's how the setTimeout() function works, it takes the function that should be delayed as a parameter (argument).
But you can, of course, call the other functions from Func1().


Darren Kulp - May 24 2006 - 11:15

The real problem is that this method cannot delay a function's return, which makes for very inelegant code in some cases.


formoney - Jun 20 2006 - 16:27

Do not we have any javascript function which delays the current function in which it is called like Thread.Sleep function.


Mike - Jul 13 2006 - 08:28

This isn't good in all cases, but it worked for what I needed. It was part of a larger class function, but you can break it out if you need. I usually set "var my = this" at the beginning of any JS class for prettiness, so within the class you'd call this like: my.Sleep(5); Outside the class, can also call it using whatever you set the object name as (objMyClass.Sleep(5)). Oh... I usually give odd internal function names like that... since they are more or less irrelevant, I like to get creative =]

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!");
}

Anyway, there you go.
-mike


Matt - Aug 10 2006 - 12:08

This is basically the same thing that mike said, just condensed into an easy to use function

function wait(msecs)
{
var start = new Date().getTime();
var cur = start
while(cur - start < msecs)
{
cur = new Date().getTime();
}
}

to use:

alert(\"Will wait for one second\");
wait(1000);
alert(\"Finished waiting\");

Not exactly sure about the resolution, but it is close enough for goverment work.


Alvaro - Sep 11 2006 - 15:23

I think (tested) that use a for/while makes hard CPU use.
I don't know why people don't like to use setTimeout, since it's the only standard-crossbrowser tool developers have, and offer work asynchronously.
What I can't figure out is how to make a easy function that idles N msecs...
Saludos!!


Damodar - Mar 09 2007 - 06:51

Hi

I am working on a project where I am triggering an onMouseover event on the links that are related to file names for displaying the the file properties on a popup window using AJAX. I wanted to delay my ajax call so that when an user moves his mouse over the page it will not hit the database needlessly. I want to make one second delay before the call. But I can't succeed doing this. You will be highly appreciated if you help me out as soon as possible.


cain - Jun 04 2007 - 19:34

Hi everyone,

For example, i want to show my table values, but each one within a time delay, as following.

cell_1_1 ...(time)...cell_1_2...(time)...cell_1_3...

I haven't found how to do it with setTimeOut function.

if sombpdy knows, please let me know.

Saludos!!!


hryniak - Jul 07 2007 - 07:36

I use setTimeout for bliking my row table. When i using while for wait cpu then i have hard usage CPU. SetTimeout is light for CPU and browser and it worls pretty well, buuut:) example don\'t use pointer to object tr, just id name ( somtimes i\'m lazy ;)

function burn_row( param, iter, delay )
{
this_row = document.getElementById( param );

if( iter <= 0 ) return;

if( iter % 2 )
this_row.style.background = \'#00FF00\';
else
this_row.style.background = \'#FF0000\';

func_def = \"burn_row( \'\"+param+\"\', \"+(iter-1)+\", \"+delay+\");\";
setTimeout( func_def, delay );

return;
}

calling:





hryniak



Add your comment:
Name:
Email:
Comment:
Please enter the Verification value character in the text box:
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons