0

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.

15
  • 1
    probably just a typo: ` <td id="p">02</td>` should probably be ` <td id="1">02</td>` Commented Jan 17, 2014 at 22:29
  • 1
    Before adding an answer, I'd just make sure you're running the javascript AFTER you're HTML is generated? Commented Jan 17, 2014 at 22:29
  • 1
    ok, next problem: str = 0 should be str === 0 Commented Jan 17, 2014 at 22:32
  • 2
    setInterval expects a function. Commented Jan 17, 2014 at 22:32
  • 1
    i = i + 1? Where's i defined? Commented Jan 17, 2014 at 22:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

that was my issue. Thanks!
1

You need to wait until your page has loaded:

document.onload = function() {
    setInterval(run_countdown("1"),1000);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.