3

I am trying to implement a simple count up timer using Javascript and show the timer in the HTML page. This is my code:

var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);

function setTime()
{
    ++totalSeconds;
    secondsLabel.innerHTML = pad(totalSeconds%60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}

function pad(val)
{
    var valString = val + "";
    if(valString.length < 2)
    {
        return "0" + valString;
    }
    else
    {
        return valString;
    }
}

HTML:

<label id="minutes">00</label>
    <label id="colon">:</label>
    <label id="seconds">00</label>

But the timer is not working in the HTML. It stays at 00:00

3
  • Try using setInterval(). You can learn about it here. Commented Dec 1, 2020 at 5:30
  • can you show the complete html page? I have copied the same code and it is working fine for me. <script type="text/javascript" src="yourfile.js"></script> Commented Dec 1, 2020 at 5:32
  • Yes the code works in the snippet, but for some reason it does not work on my end Commented Dec 1, 2020 at 5:37

3 Answers 3

2

Make sure the script is at the bottom on the body tag

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

Comments

1

The code you posted works exactly as you describe.

Check this fiddle, I just copy pasted it.

.

4 Comments

Yes the code works in the snippet, but for some reason it does not work on my end
Then some other part of your code must have an error. Can you please check your console?
yeah I had the script at the beginning of the body. Had to move it to the closing tag of the body
@efuzz Indeed, getElementById (or any other function that gets DOM nodes) will not work unless the nodes already exist. You can either move your script to the bottom of the body or wrap it in an onload function.
0

The code you mentioned is working perfectly fine in the snippets.

1 Comment

Yes the code works in the snippet, but for some reason it does not work on my end

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.