question
question

Reputation:

Javascript timing problem

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.

Upvotes: 1

Views: 837

Answers (6)

Leo
Leo

Reputation: 1811

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

Upvotes: 0

Ming-Tang
Ming-Tang

Reputation: 17651

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.

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

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.

Upvotes: 2

user110714
user110714

Reputation:

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

Upvotes: 2

Paul
Paul

Reputation: 1264

setTimeout - executes code after a time interval

clearTimeout - cancels the setTimeout()

More details here.

Upvotes: 0

John Feminella
John Feminella

Reputation: 311496

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

Upvotes: 0

Related Questions