0

I wanted to do something like this:

<p id="sec">5</p>
<script>
var i = 5;
while (i > 0){
    setTimeout(i--,1000);
    document.getElementById("sec").innerHTML = i;
}
if (i === 0){
    window.location = "index.php";
}
</script>

And without a split second, it redirected me to index.php? Why does this happened? How to make it work?

4
  • 1
    setTimeout takes a function to execute sometimes later, and returns immediately. Commented Feb 8, 2013 at 12:28
  • replace your setTimeout with: setTimeout(alert("hi!"),1000); and you will understand what's happening really. PS: remove the redirect, just for testing purposes. Commented Feb 8, 2013 at 12:30
  • @TheBronx The "sec" stayed 5?! Sorry but I don't understand. Commented Feb 8, 2013 at 12:32
  • you have to understand that setTimeout does not stop execution of the script. It's not like a "sleep" function. A more simple example, two lines: setTimeout(function(){alert("timeout finished!")},5000);alert("hey, no waiting"); See what happens, which alert comes first? Commented Feb 8, 2013 at 12:36

1 Answer 1

3
var i = 5;
setTimeout(updateTime,1000);

function updateTime()
{
    document.getElementById("sec").innerHTML = i--;

    if (i === 0)
        window.location = "index.php";
    else
        setTimeout(updateTime, 1000);
}
Sign up to request clarification or add additional context in comments.

8 Comments

I tried but the sec stayed 5 also.
works just fine here: jsfiddle.net/aXKB3
+1, This is the best answer here because it won't lock up the CPU. Also because your name is Paul. This could also be achieved using window.setInterval.
@DanielCheung check the javascript console for errors
@PaulS. some people shun setInterval
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.