JavaScript计时器从一定时间倒计时数小时

时间:2015-05-06 13:53:56

标签: javascript timer countdown

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

我已经从17 hours 00 minutes 00 seconds开始计时器倒计时,它可以解决问题,但我需要一种方法从00:00:00取消17 hours到现在的时间。< / p>

这是我的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并取消差异。

1 个答案:

答案 0 :(得分:2)

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

&#13;
&#13;
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);
};
&#13;
<div>Order by: <span id="time"></span> for Next Day Delivery.</div>
&#13;
&#13;
&#13;

jsFiddle

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