How can I use setInterval or setTimeout and display the results during the count?

javascript

Solution

function countDown(i) {
    var int = setInterval(function () {
        document.getElementById("displayDiv").innerHTML = "Number: " + i;
        i-- || clearInterval(int);  //if i is 0, then stop the interval
    }, 1000);
}
countDown(5);

DEMO: http://jsfiddle.net/DerekL/sFtqZ/ (extra callback argument included)

Problem

I'm trying to make a timer count down from 5 seconds to zero before a function is called, and I can do that successfully, but I haven't yet been able to display the timer value as it counts down. Instead of displaying the values, the `<div></div>` goes from a blank space to "Number: 0". I've used both `setTimeout` and `setInterval` with the same result. ``` <script type="text/javascript"> for (i = 5; i > 0; i--) { function countDown() { setInterval(function () { document.getElementById("displayDiv").innerHTML = "Number: " + i; }, 1000); } } </script> ``` I also tried using `.value` in place of `.innerHTML` with no help. ``` <input type="button" value="Count" onclick="countDown()" /> <div id="displayDiv" /> ``` This seems like it should be really simple, but it has me stumped. Any help is appreciated

Original source

Related problems