Geekpedia Programming Tutorials






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

On Wednesday, September 21st 2005 at 06:13 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.3 with 7 votes)
Advertisement
More JavaScript Resources
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
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this Knowledge Base article
Comment Current Comments
by HSIM on Thursday, November 24th 2005 at 03:45 AM

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.

by Andrei Pociu on Thursday, November 24th 2005 at 04:53 AM

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().

by Darren Kulp on Wednesday, May 24th 2006 at 11:15 AM

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

by formoney on Tuesday, June 20th 2006 at 04:27 PM

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

by Mike on Thursday, July 13th 2006 at 08:28 AM

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

by Matt on Thursday, August 10th 2006 at 12:08 PM

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.

by Alvaro on Monday, September 11th 2006 at 03:23 PM

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!!

by Damodar on Friday, March 9th 2007 at 06:51 AM

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.

by cain on Monday, June 4th 2007 at 07:34 PM

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!!!

by hryniak on Saturday, July 7th 2007 at 07:36 AM

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:

<table>
<tr id=\"moj_tr\" onClick=\"burn_row( \'my_tr\', 10, 3000 );\">
<td>hryniak</td>
</tr>
</table>

by Mike on Friday, October 3rd 2008 at 12:05 PM

Thanks for the help!
It worked great!!

by dponnet on Wednesday, December 3rd 2008 at 02:23 AM

Thanks, it works great!!

by sasi on Saturday, December 27th 2008 at 12:46 AM

in javascript how to do a program that a advertisement is given on the top of a webpage that AD should change for every 10 sec

by http://www.mofun.cc on Tuesday, March 24th 2009 at 07:59 AM

Thanks a lot!


Comment Comment on this Knowledge Base article
Name: Email:
Message:
Knowledge Base Related Knowledge Base Articles
There are no related KB articles.

Comment Related Source Code
There is no related code.

Comment Related Tutorials
There are no related tutorials.

Jobs JavaScript Job Search
My skills include:

Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons