简体   繁体   中英

How to format the elapsed time of setInterval method JavaScript

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!

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);
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM