代码之家  ›  专栏  ›  技术社区  ›  user3108268

如何自动重置倒计时?

  •  0
  • user3108268  · 技术社区  · 5 年前

    // Set the date we're counting down to
    var countDownDate = new Date("Dec 30, 2019 15:37:25").getTime();
    
    // Update the count down every 1 second
    var x = setInterval(function() {
    
      // Get today's date and time
      var now = new Date().getTime();
    
      // Find the distance between now and 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);
    
      // Display the result in the element with id="demo"
      document.getElementById("demo").innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";
    
      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
      }
    }, 1000);
    <p id="demo"></p>

    如何重置每年的倒计时?如何使年在 var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime(); 这样你就不需要为每个新年编辑.js文件了?

    一旦2019年到期,它就会重新开始,并开始计算2020年12月30日,以此类推?

    2 回复  |  直到 5 年前
        1
  •  1
  •   dikuw    5 年前

    不如根据今天的日期动态获取年份:

    // Set the date we're counting down to
    dt = new Date();
    year = dt.getFullYear();
    var countDownDate = new Date(year,11,30,15,37,25).getTime();
    
    // Update the count down every 1 second
    var x = setInterval(function() {
    
      // Get today's date and time
      var now = new Date().getTime();
    
      // Find the distance between now and 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);
    
      // Display the result in the element with id="demo"
      document.getElementById("demo").innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";
    
      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
      }
    }, 1000);
    <p id="demo"></p>
        2
  •  1
  •   Robin Rozo    5 年前

    你可以用 日期。GetFullYear() 方法获取当前年份并使用它来构建 countDownDate 是的。

    var year = new Date().getFullYear();
    var countDownDate = new Date("Dec 30, " + year + " 15:37:25").getTime();