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

时间:2021-01-24 02:47:43

I am trying to create a countdown timer, struggling to make it show hours, then minutes, then seconds.

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

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

Struggling to get minutes and hours displaying correctly.

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

As well as this I need the timer to start at midnight and countdown for 17 hours. Thinking along the lines of 3600 * 17 (17 hours) then take off the duration left?

除此之外,我需要计时器在午夜开始并倒计时17个小时。沿着3600 * 17(17小时)的思路然后离开的时间呢?

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

1 个解决方案

#1


You have a typo and 2 minor computation flaws:

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

function timer:

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

onload-Handler:

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

#1


You have a typo and 2 minor computation flaws:

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

function timer:

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

onload-Handler:

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