Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 291
JonDoeCA Avatar asked Jun 18 '12 00:06

JonDoeCA


2 Answers

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)

like image 51
Derek 朕會功夫 Avatar answered Nov 01 '22 13:11

Derek 朕會功夫


try

<script type="text/javascript">
function countDown() {
var i = 5;
var myinterval = setInterval(function() {
    document.getElementById("displayDiv").innerHTML = "Number: " + i;

    if (i === 0) {
        clearInterval(myInterval);
        //call your function
    }
    else {
        i--;
       }
    }, 1000);
}​
</script>

http://jsfiddle.net/pjSKa/

like image 36
Brett Smith Avatar answered Nov 01 '22 11:11

Brett Smith