javascript - 如何自动重置倒计时?

标签 javascript

// 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 日,依此类推?

最佳答案

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

// 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>

关于javascript - 如何自动重置倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58419420/

相关文章:

javascript - 从 AJAX 请求返回 while 循环

javascript - 从提供者函数获取值到另一个页面

javascript - node.js -- 从回调函数中获取数据

javascript - 在 node.js 中捕获需要模块的错误

javascript - 如何在 redux 中创建/编辑/删除嵌套结构?

asp.net - 如何获取服务器上唯一的客户端标识符?

javascript - 如何提交新帖子?

javascript - 尝试开发绘画程序

javascript - 使用严格模式时如何从 JavaScript 对象中删除属性

javascript - JQuery 函数可以在开发控制台上运行,但不能在加载页面中运行