JavaScript 计时器从特定时间开始倒计时数小时

JavaScript timer to count down from a certain time for a number of hours

我创建了一个倒数计时器。问题是,我想让它从午夜时钟 00:00:00 倒数到时钟 17:00:00

我已经让计时器从 17 hours 00 minutes 00 seconds 开始倒计时,这很有用,但我需要一种方法来减少从 00:00:0017 hours 的时间.

这是我的 JS 代码

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

这是我的 HTML 代码:

<div>Order by: <span id="time"></span> for Next Day Delivery.</div>

我的想法是获得 timeLeft = 3600 * 17 并消除差速器。

这是您更正的代码:保存当天 17 点的时间戳(如果我们在 17 点之后,则为第二天)并将其与当前时间戳进行比较更容易。要计算剩余小时数,您必须将秒数除以 3600 (60*60) 而不是 360

function startTimer(display) {
    var date = new Date();
    var h17 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 17);
    if(date.getHours() >= 17) {
        h17.setDate(h17.getDate()+1);
    }
    h17 = h17.getTime();
    var diff,
        hours,
        minutes,
        seconds;
    
    function timer() {
        diff = (((h17 - Date.now()) / 1000) | 0);
        
        // Setting and displaying hours, minutes, seconds
        hours = (diff / 3600) | 0;
        minutes = ((diff % 3600) / 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;
    };
    timer();
    setInterval(timer, 1000);
}
window.onload = function () {
    var timeLeft = 3600 * 17,
        display = document.querySelector('#time');
    startTimer(display);
};
<div>Order by: <span id="time"></span> for Next Day Delivery.</div>

jsFiddle

PS : 我没有测试功能是否在 17 小时后正常工作,但它应该