Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sleep() function 1

Status
Not open for further replies.

luciddream

Programmer
Nov 8, 2000
712
US
if anyone has every been upset that javascript doesn't have a sleep function, i just wrote one. it doesn't wait the exact amount of time.... but, it's really close.

so:

function sleep(num)
{
var f = new Date();
f = new Number(f);
f = f + num;
while(true)
{
var n = new Date()
n = new Number(n);
if(n >= f)
{
break;
}
}
}


then you just call it like:

sleep(5000);

where 5000 is the number of milliseconds you want it to sleep for. adam@aauser.com
 
isn't that what the setTimeout function is for?

theEclipse
eclipse_web@hotmail.com
robacarp.webjump.com
**-Trying to build a documentation of a Javascript DOM, crossbrowser, of course. E-mail me if you know of any little known events and/or methods, etc.
 
well, setTimeout will not stop for example the execution of a for loop... this does. say for example you wanted to use a for loop to have alerts spread out 5 seconds apart, then to execute some code afterward...


for(i = 0;i < 5; i++)
{
setTimeout(&quot;alert('unf');&quot;, 5000);
}
alert('hello');

in all liklihood, the hello alert will appear first, then the five alerts of unf.

using sleep however...

the 5 unf alerts will execute first. each roughly 5 seconds apart, then the alert hello. adam@aauser.com
 
very nice. jared@aauser.com
 
i see, but why did you choose to use the date object? is that just a filler?
theEclipse
eclipse_web@hotmail.com
robacarp.webjump.com
**-Trying to build a documentation of a Javascript DOM, crossbrowser, of course. E-mail me if you know of any little known events and/or methods, etc.
 
no, it loops till it has been the specified number of seconds from when you run it. it gets the date when you call it, it calculates the date for however many milliseconds in the future you specify, then get's a new Date() every iteration and tests that against the date in the future. adam@aauser.com
 
verry nice

theEclipse
eclipse_web@hotmail.com
robacarp.webjump.com
**-Trying to build a documentation of a Javascript DOM, crossbrowser, of course. E-mail me if you know of any little known events and/or methods, etc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top