将startdate设置为倒计时

时间:2018-06-15 10:00:51

标签: javascript countdown

我的倒计时结束于特定的时间和日期 是否可以设置倒计时的开始日期?

开始:2018年6月14日15:00:00
结束:2018年6月17日23:59:59

v3.1.2
// Set the date we're counting down to
var countDownDate = new Date("June 17, 2018 23:59:59").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
    // Output the result in an element with id="demo"
    document.getElementById("countdown").innerHTML = "TEXT Countdown" + days + " days, " + hours + " h, "
    + minutes + " min & " + seconds + " sec";
    
    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("countdown").innerHTML = "TEXT after countdown";
    }
}, 1000);

1 个答案:

答案 0 :(得分:0)

将呼叫延迟到setInterval,直到您想要的时间。你最好的选择,因为计时器在非活动标签上被限制,是定期检查,然后在时间到来时启动:

var waitingTimer = setInterval(function() {
    if (Date.now() < Date.parse("2018-06-14T15:00:00")) {
        return;
    }
    clearInterval(waitingTimer);
    // ...start the countdown
}, 1000);

您可能希望以UTC表示时间,因为遗憾的是,如果没有时区指示符更改(两次),这些字符串意味着什么,而如果您将时间设置为UTC并在字符串中添加Z ,它很可靠。