1

I have a simple setInterval setup like so:

var time = 0;
function a(){
    window.setInterval(timer, 1000);
}

Which executes this function:

function timer() {
    time +=1;
    document.getElementById("a").innerHTML = time + "s"
}

HTML is very simple for this. It just displays as 0s and increases.

The problem I am having is that I can't seem to get it to display in a format like this 00:00:00.

Any help is much appreciated!

Geroy290
  • 468
  • 2
  • 9
  • 24

2 Answers2

2

Give this a shot, using JS's built-in Date class, taken from here:

function timer() {
  var date = new Date(null);
  date.setSeconds(time++);
  document.getElementById("a").innerHTML = date.toISOString().substr(11, 8);
}
Community
  • 1
  • 1
RobertAKARobin
  • 3,933
  • 3
  • 24
  • 46
0

Create timer element

<div id="timer">
    <span class="hours"></span>
    <span class="minutes"></span>
    <span class="seconds"></span>
</div>

Style

#timer > .hours:after,  #timer > .minutes:after{
    content: ":";
}

Update timer

var Timer = function(element){
    var secondsElement = element.getElementsByClassName("seconds")[0],
        minutesElement = element.getElementsByClassName("minutes")[0],
        hoursElement   = element.getElementsByClassName("hours")[0],
        show = function(num){
            return ("0" + num).slice(-2);
        };

    return {
        update: function(){
            var now = new Date();
            secondsElement.innerHTML = show(now.getSeconds());
            minutesElement.innerHTML = show(now.getMinutes());
            hoursElement.innerHTML   = show(now.getHours());
        }
    };
};

var timer = new Timer(document.getElementById("timer"));

setInterval(function(){
    timer.update();
}, 500);
Nishant
  • 4,659
  • 2
  • 27
  • 43