setTimeout?

  • Thread starter Better but still clumpsy
  • Start date
B

Better but still clumpsy

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.
 
M

Michael Winter

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,235
Latest member
Top Crypto Podcasts_

Latest Threads

Top