Reputation: 10792
I'm trying to test out a simple recursive function to make a countdown timer. So far I have this javascript function:
setInterval(run_countdown("1"),1000);
function run_countdown(num) {
var str = document.getElementById(num).innerHTML;
if(str === 0){
str = 59;
num = num + 1;
run_countdown(num)
}
var minus = str - 1;
var res = str.replace(str,minus);
document.getElementById(num).innerHTML=res;
return;
};
and this is the markup in the browser:
<table border="0">
<tbody>
<tr>
<td id="6">00</td>
<td id="5">00</td>
<td id="4">08</td>
<td id="3">02</td>
<td id="2">42</td>
<td id="1">02</td>
</tr>
<tr>
<th>Years</th>
<th>Months</th>
<th>Days</th>
<th>Hours</th>
<th>Minutes</th>
<th>Seconds</th>
</tr>
</tbody>
</table>
When I run the page in the browser, I get an error in the consol saying "Uncaught TypeError: Cannot read property 'innerHTML' of null" for the very first getElementById. I did an alert on num and it seemed to be passing in ok. Not quite sure where I'm going wrong.
Upvotes: 0
Views: 177
Reputation: 863
You need to wait until your page has loaded:
document.onload = function() {
setInterval(run_countdown("1"),1000);
}
Upvotes: 1
Reputation: 2771
as elchlanrs said, setInterval takes a function reference. Try
setInterval(function(){
run_countdown("1");
}, 1000);
This will wait a full second before calling run_countdown("1"), presumably allowing your document to finish loading before execution which should fix the error.
Upvotes: 2