一个简单的倒数计时器,显示小时,分钟,秒

时间:2015-05-06 10:38:29

标签: javascript timer

我正在尝试创建一个倒数计时器,努力让它显示小时,然后是分钟,然后是秒。

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

        // Setting and displaying hours, minutes, seconds
        hours = (diff / 360) | 0;
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 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 17:00:00 not 16:59:59
            start = Date.now() + 1000;
        }
    };
    // don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}
window.onload = function () {
    var timeLeft = 3600 * 17,
        display = document.querySelector('#time');
    startTimer(timeLeft, display);
};

努力让分钟和小时正确显示。

除此之外,我需要计时器在午夜开始并倒计时17个小时。按照3600 * 17(17小时)的路线思考,然后取消剩下的时间?

var timeLeft = ((3600 * 17) - diff),

1 个答案:

答案 0 :(得分:2)

你有一个错字和2个小的计算缺陷:

功能计时器:

 hours   = (diff / 3600) | 0; // was: hours = (diff / 360) | 0;
 minutes = ((diff % 3600) / 60) | 0;

的onload处理程序:

var hoursMinutesSeconds = 3600 * 17, // was: 360 * 60 * 17; alternative: 60 * 60 * 17
display = document.querySelector('#time');