Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

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.1 with 39 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!

by pu on Wednesday, July 15th 2009 at 01:57 AM

abey dhakkan..
tera code chalta toh hai nahi...
nalayak.. next time aisa code diya to pitega

by Miller on Saturday, August 15th 2009 at 09:29 AM

if you want to kill the events while waiting then listen all events on client side and kill them before the browser delivers them to server.
this is the way. this is same as setting return value to false setting some other vars too.

by sksoftmind on Friday, September 11th 2009 at 08:53 AM

do or do while will use cpu so dont use it please thanks

by sunil on Friday, September 11th 2009 at 09:23 AM

some usefull links for sleep wait javascript

<script type="text/javascript"><!--
google_ad_client="pub-1067033232109611";
google_ad_host="pub-1556223355139109";
google_ad_width=120;
google_ad_height=90;
google_ad_format="120x90_0ads_al_s";
google_color_border="FFFFFF";
google_color_bg="FFFFFF";
google_color_link="0000FF";
google_color_url="0000FF";
google_color_text="0000FF";
//--></script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

by ksdjf on Friday, September 11th 2009 at 09:24 AM

</div><div>

by Atiq khattak on Thursday, October 8th 2009 at 02:36 AM

i have s serious problem. any one help me

i want a div that have loaded like a popup menu from top left side after 10 second when a window is loaded.
send me code on my id atiqkhan2011@yahoo.com
Regards!

by Kirbdawg on Thursday, October 22nd 2009 at 04:49 AM

function wait(milsecs){
var to_time = new Date().getTime() milsecs;
while( new Date().getTime() < to_time ){}
return true;
}

do_something_first();
wait(500);
now_do_something_else();

by Kirbdawg on Thursday, October 22nd 2009 at 04:51 AM

^ there should be a plus sign on the 2nd line above to add getTime() to milsecs (it got removed when I submitted this)

by therealdeal on Monday, November 9th 2009 at 06:34 PM

I researched about javascript sleep and nobody has a solution that does not uses up a lot of cpu time running useless loops.

here is my solution:
example::


<html>
<body>
<script>
//javascript sleep by therealdeal
//global var
var i = 0;
function start()
{
dothese(i);
i ;
timer(); //runs a timer to run start()
}

function dothese(ij) {
if (ij==0){alert('0');}
if (ij==1){alert('1');}
if (ij==2){alert('2');}
if (ij > 2){alert(ij);}
}

function timer() {t=setTimeout("start()",1000);} //can be a lot more than this

start();
</script>
</body>
</html>

by therealdealsince1982 on Monday, November 9th 2009 at 10:38 PM

cleaned up some code after dinner,
added some variaions::

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function flow() {
run(i);
i ; //code segment finished running, increment i; can put elsewhere
sleep(1000);
if (i==5) {clearTimeout(t);} //stops flow, must be after sleep()
}

function run(segment) {
//pieces of codes to run, can use switch statement
if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow
</script>
</body>
</html>

//................................

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout, switch
var i = 0;

function flow() {
switch(i)
{
case 0:
run(i);
sleep(1000);
break;
case 1:
run(i);
sleep(2000);
break;
case 5:
run(i);
clearTimeout(t); //stops flow
break;
default:
run(i);
sleep(3000);
break;
}
}

function run(segment) {
//pieces of codes to run, can use switch statement
if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment " segment " is ran</p>"; }
i ; //current segment of code finished running, next...
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow control for first time...
</script>
</body>
</html>

///..................................

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setInterval
var i = 0;

function run() {
//pieces of codes to run
if (i==0){document.getElementById("id1").innerHTML= "<p>code segment " i " is ran</p>"; }
if (i==1){document.getElementById("id1").innerHTML= "<p>code segment " i " is ran</p>"; }
if (i==2){document.getElementById("id1").innerHTML= "<p>code segment " i " is ran</p>"; }
if (i >2){document.getElementById("id1").innerHTML= "<p>code segment " i " is ran</p>"; }
if (i==5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } //end interval, stops run
i ; //segment of code finished running, next...
}

t=setInterval("run()",1000);

</script>
</body>
</html>

by pepe on Friday, December 25th 2009 at 10:30 PM

My solution? Make use of eval and setTimeout.

Create an array with the timeouts and the commands to execute something like:

var todo=[
100,"ShowImage('firstimage.jpg')",
150,"ShowImage('secondimage.jpg'",
250,"ModifyOtherStuff(params)"]

And create a function that goes through the array with eval, like this:

var pos=0;

function go()
{
eval (todo[pos 1]);
var tm=todo[pos];
pos =2;
if (pos<todo.length)
setTimeout ("go",tm);
}

by Alex on Tuesday, December 29th 2009 at 03:04 AM

In all ohesty, that's a lousy solution - what if I need to delay exiting the current function???
For example, function A is called from outside (not my code), and i need to delay the execution of the exterior code for some time, I can't possibly do that with setTimer, as i exit function A

by Alex on Tuesday, December 29th 2009 at 03:11 AM

just goes to show that my initial claim was right - javascript is a lousy language with no amenities whatsoever, very low support from the operating system, (as is evident by the lack of the Sleep function that is a must)

by Anthony on Wednesday, February 17th 2010 at 05:10 PM

Hey, umm, I'm making my own site and finnally half uploading it, umm, what is the code in order to download it, like some sites do like rapidshare does that seconds time limist for regular download. then it changes into that button. what is that source code.. plz and thankyou

by abc on Monday, March 8th 2010 at 11:40 AM

function sleep(delay)
{
var start = new Date().getTime();
while (new Date().getTime() < start delay);
}

by sds on Thursday, June 24th 2010 at 06:37 AM

efreferfreferfef

by pckhoi on Wednesday, August 11th 2010 at 11:17 PM

After seeing all the comments, I think the only way that setTimeout can ever truly replace sleep is when you call it last, in your entire javascript. setInterval works much the same way.


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 >>
Sponsors
Discover Geekpedia

Other Resources