setTimeout?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Better but still clumpsy

    setTimeout?


    Hi,

    I have a script that is looping like this :

    for (i=0;i<100;i++)
    {
    do 1
    do 2
    display
    setTimeout("tim er",1000);
    while (timer!=null) process_event_p ending();// 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.
  • Michael Winter

    #2
    Re: setTimeout?

    Better but still clumpsy wrote:

    [snip]
    [color=blue]
    > setTimeout("tim er",1000);
    > while (timer!=null) process_event_p ending();// in Window C[/color]

    You misunderstand what setTimeout does.

    timerId = setTimeout(pCal lback, ms);

    is equivalent to

    timerId = SetTimer(NULL, 0, ms, pCallback);
    [color=blue]
    > clearTimeout;[/color]

    and

    clearTimeout(ti merId);

    is equivalent to

    KillTimer(timer Id);

    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]
    [color=blue]
    > So, is there anyway to wait for time out?[/color]

    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('wai t=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.c om/faq/faq_notes/misc.html#mtSet TI>

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.

    Comment

    Working...