如何为倒数计时器添加格式小时/分钟/秒

时间:2015-12-08 09:34:07

标签: javascript timer countdown

我对计时器倒计时感到困惑, 我试着改变,但坚持小时格式, 我从链接获得如下所示的代码倒计时 The simplest possible JavaScript countdown timer?



function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
&#13;
&#13;
&#13;

我想在这个javascript中添加小时,格式为60:60:60 / hh / mm / ss

谢谢你:)

1 个答案:

答案 0 :(得分:1)

查看this是否可以为您提供帮助。 这是显示小时的代码:

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        hours,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float

        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        if(minutes >= 60){
           hours = (minutes / 60) | 0;
           minutes = (minutes % 60) | 0;
        }else{
           hours = 0;
        }

        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = hours + ":" + minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};