Hi !
Is there any way for a javascript statement to get executed, only after another function is finished, or a functionality something like "sleep" function. Sample code is appreciated.
Where the functionOrStatement part of the function is any valid javascript statement or function.
But, for this particular question, I'd probably stick to calling the function inside (and at the end, no less) of the function that you want to finish executing before you call the other...
//sleep function. stops execution for specified milliseconds.
function sleep(num)
{
var f = new Date();
f = new Number(f);
f = f + num;
while(true)
{
var n = new Date();
n = new Number;
if(n >= f)
{
break;
}
}
} luciddream@subdimension.com
luciddream, what does the processor on the machine that runs this code look like while this function is "sleeping"?
Isn't it pegged out?
What is the advantage of using this code over using something like the setTimeout() function? Would the setTimeout not be friendlier on the processor?
I'm curious to know because whenever I try to make a function (or code) "sleep", I try not to use that while looping because it just cycles like mad -- eating up my resources.
well, the only advantage to using a sleep function is that if you want a pause in the middle of your code, you don't have to put the rest of your code in a separate function. also, setTimeout()'s don't wait for you to finish with modal components.... for example... try these two pieces of code...
for(var i = 0; i < 5; i++)
{
setTimeout('alert()', 5000);
}
and:
for(var i = 0; i < 5; i++)
{
alert()
sleep(5000);
}
the second one actaully waits five seconds between alerts, where the first pops them all up one after the other.
its not very practical or efficient, but, it does work. luciddream@subdimension.com
Thanks alot. Another question, is there any optimal value for the timeinterval for setTimeout or setInterval method, so, that would not cause a problem in low config systems.
I agree with link9 that setTimeout seems preferable to a loop. Would the following work?
var count=5; // using the given example
var num=5000;
var test;
// Does it need "test"?
function sleep() {
if (count>0) {
alert();
count--;
test=setTimeout("sleep();",num);
}
else clearTimeout(test);
}
// or would this be sufficient?
function sleep() {
if (count>0) {
alert();
count--;
setTimeout("sleep();",num);
}
}
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.