A 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.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This 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.
Creating 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.
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) |
||
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()).
Then you simply call Func1Delay() which in turn calls Func1() but with a delay of 3000 milliseconds (3 seconds):
|
|||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
|||
|
|||
Current CommentsWait 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.
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().
The real problem is that this method cannot delay a function's return, which makes for very inelegant code in some cases.
Do not we have any javascript function which delays the current function in which it is called like Thread.Sleep function.
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
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.
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!!
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.
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!!!
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>
Thanks for the help!
It worked great!!
Thanks, it works great!!
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
Thanks a lot!
abey dhakkan..
tera code chalta toh hai nahi...
nalayak.. next time aisa code diya to pitega
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.
do or do while will use cpu so dont use it please thanks
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>
</div><div>
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!
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();
^ there should be a plus sign on the 2nd line above to add getTime() to milsecs (it got removed when I submitted this)
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>
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>
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);
}
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
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)
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
function sleep(delay)
{
var start = new Date().getTime();
while (new Date().getTime() < start delay);
}
efreferfreferfef
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.
Related Knowledge Base Articles
Related Source Code
Related Tutorials
JavaScript Job Search