Wednesday, April 6, 2011

Sleep in Javascript

Any way I can do a sleep in javascript before it's carry another action?

Example:

 var a = 1+3;
 // sleep 3 seconds before the next action here
 var b = a + 4;
From stackoverflow
  • You can use setTimeout to achieve a similar effect:

    var a = 1 + 3;
    var b;
    setTimeout(function() {
        b = a + 4;
    }, (3 * 1000));
    

    This doesn't really 'sleep' JavaScript—it just executes the function passed to setTimeout after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use setTimeout if possible as it doesn't freeze everything during the sleep period.

    Steve

    Anders Sandvig : Also have a look at setInterval(). It's similar to setTimeout(), but your function is called multiple times (until you stop it), which is useful if you want to do something while sleeping (like doing progress updates, keeping some internal state, or whatever).
  • setTimeout ( "doSomething()", 5000 );
    
    function doSomething ( )
    {
      // (do something here)
    }
    

    IMPORTANT: make sure you put quotes around the function you would like to call with setTimeout().

    setTimeout() doesn't halt the execution of the script during the timeout period. It just schedules the specified expression to be run at the specified time.

    Javier : when quoted that way, you're passing a string to be executed, that means it will be eval()'ed in a new environment. much better is to pass the actual function. if defined in place (an anonymous function) you get a closure, which can refer to local variables, even after the calling function is done
    Jimmie R. Houts : Javier is correct, see this page for an explanation: http://dev.opera.com/articles/view/efficient-javascript/?page=2

0 comments:

Post a Comment