使用setTimeout()时的javascript倒计时器问题

时间:2018-02-13 23:00:28

标签: javascript html

倒计时器不会加载 - 仅在页面刷新后才会加载。

我已经在codepen.io等上测试了代码,但是当在网站上托管时,倒计时没有出现,它只在刷新后才会出现。

当我使用setInterval()时,它可以正常工作,但是我只想倒计时一次更新倒计时,因此使用了setTimeout()



// Set the date we're counting down to
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();

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

    // Get date
    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));
    
    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = days + " days left	";
    
    // If the count down is over, write some text 
    if (distance < 0) {
        clearTimeout(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 300);
&#13;
&#13;
&#13;

完整代码:https://codepen.io/anon/pen/VQzMdG

1 个答案:

答案 0 :(得分:1)

您可以创建data-attribute,即:updateCountdown。这将是仅更新倒计时一次的标志。

// Set the date we're counting down to
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {
  // Get date
  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 demo = document.getElementById("demo");
  if (!demo.dataset.updateCountdown) {
    console.log('Update countdown.');
    demo.dataset.updateCountdown = false;
       
    // Output the result in an element with id="demo"
    demo.innerHTML = days + " days left	";
  }

  console.log(x)
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 2000);
<span id='demo'></span>

请参阅?现在它只更新了一次。

资源