views:

251

answers:

6

I wont to run a block of code in a certain amount of time and then when done, carry on with another block of code.

A: 

You'll want to use the setTimeout() function.

John Feminella
A: 

setTimeout - executes code after a time interval

clearTimeout - cancels the setTimeout()

More details here.

Paul
+2  A: 

Using the setTimeout() is probably what you want. For example...

<script type="text/javascript">
    function YourFunction()
    {
        alert('Hello Stackoverflow');
    }

    window.setTimeout(YourFunction, 1000);
</script>

Hope it helps

Chalkey
+2  A: 

This is how you would do it, using the setTimeout function, which takes code to call as the first argument and how much time it should wait before calling it (in milliseconds) as the second argument:

function callWhenDone() {
    // code to call when timeout finishes
}

setTimeout(function() {
    // initial code to run
    callWhenDone();
}, 5000); // 5000 = run in 5 seconds

Because of the nature of Javascript you have to encapsulate the code you want to run after the timeout is finished in its own function, otherwise it would be run before the timeout is finished. This is, in essense, a callback, and it is a big part of the event-based nature of Javascript.

Paolo Bergantino
A: 

Use setTimeout.

setTimeout(function() {
    // code here
    // you can use it recursively
    //   setTimeout(...);
  },
  1000 // 1000 miliseconds (= 1 second)
);

and setInterval is like setTimeout, except it repeats a code repeatedly.

SHiNKiROU
A: 
<script type="text/javascript">

var timer = setInterval("firstFunction()","1000"); //every second call firstFunction()
var i = 0;

function firstFunction()
{

    //first code

    i++;
    if(i == 3)
    {
        clearInterval(timer);
        secondFunction();
    }
}

function secondFunction()
{
    //second code
    alert("done!");
}

</script>
Leo