【问题标题】:Set startdate to countdown将开始日期设置为倒计时
【发布时间】:2018-06-15 10:00:51
【问题描述】:

我有一个在特定时间和日期结束的倒计时。
是否可以设置倒计时的开始日期?

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

// 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);
&lt;div id="countdown"&gt;&lt;/div&gt;

【问题讨论】:

  • var countDownDate = new Date("June 17, 2018 23:59:59").getTime(); 该字符串不在the only format new Date is required to parse 中。强烈建议使用正确的格式。即使您碰巧用于测试的浏览器中的浏览器 JavaScript 引擎可以正常工作,但这并不意味着其他人会(或在其他语言环境中)。

标签: javascript countdown


【解决方案1】:

只需延迟拨打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,它是可靠。

【讨论】:

  • 我不让它工作,你会怎么写代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多