Reputation: 407
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
Upvotes: 8
Views: 17886
Reputation: 94319
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)
Upvotes: 17
Reputation: 3052
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>
Upvotes: 4