By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,717 Members | 1,233 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,717 IT Pros & Developers. It's quick & easy.

setTimeout?

P: n/a

Hi,

I have a script that is looping like this :

for (i=0;i<100;i++)
{
do 1
do 2
display
setTimeout("timer",1000);
while (timer!=null) process_event_pending();// in Window C
do 3
clearTimeout;
}

In MS C, I can loop and yield the process until timer="";
But, it seems that I can not do it in Javascript. So, is
there anyway to wait for time out?

Thanks.
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Better but still clumpsy wrote:

[snip]
setTimeout("timer",1000);
while (timer!=null) process_event_pending();// in Window C
You misunderstand what setTimeout does.

timerId = setTimeout(pCallback, ms);

is equivalent to

timerId = SetTimer(NULL, 0, ms, pCallback);
clearTimeout;
and

clearTimeout(timerId);

is equivalent to

KillTimer(timerId);

That is, setTimeout defers execution of code until ms milliseconds has
elapsed. However, there is no pause: the function returns immediately.

The value of pCallback above can be of two forms; a string or a
function reference. With the former, the string is evaluated as code
in global scope (which can, of course, include function calls). That
is, you cannot refer to any local variables or use the this operator
(well you can, but it will refer to the global object). Using a
function reference provides much more flexibility, but it is not
supported by obsolete user agents (like NN4).

See the setTimeout article[1] in the FAQ notes for more information.

[snip]
So, is there anyway to wait for time out?


Yes, but you shouldn't. A sleep equivalent will take up all CPU time
and appear to make the user agent hang. However, implementation would
be something like

function sleep(ms) {var stop = ms + (new Date());
while(+(new Date()) < stop);
}

though timer resolution would be poor. Client-side scripting wasn't
meant to work this way so it should be avoided. Instead, move "do 3"
into a function (or just a string, if it's short) and pass it to
setTimeout. The clearTimeout method (which you don't actually call,
just evaluate) is unnecessary.

An alternative strategy might be

var wait; /* Global */

for(var i = 0; i < 100; ++i) {
wait = true;
/* do 1
* do 2
* display
*/
setTimeout('wait=false;', 1000);
while(wait) {process_event_pending();}
/* do 3 */
}

Again, note that timer resolution will be poor.

Hope that helps,
Mike
[1] <URL:http://www.jibbering.com/faq/faq_notes/misc.html#mtSetTI>

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.