javascript - 下周开始计时数据

标签 javascript timer

function countDown(){
  // Set the date we're counting down to
  var countDownDate = new Date("july 11, 2017 10:19:00").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("demo").innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";

      // If the count down is over, write some text 
      if (distance < 0) {
          countDownDate = new Date("july 18, 2017 10:19:00").getTime();
      }
  }, 1000);

}

countDown();

我想要达到的是每周计时器都会开始计数到下周。 我每周都会在同一天同一时间开始一些事情。

我不想每周都重写代码:/

谢谢。

最佳答案

那么为什么仅仅为了计算距离下周开始还剩多少秒就需要如此多的计算呢?例如,我正在编写示例代码来计算它。

function distranceToNextWeekStartInSeconds() {
    var now = new Date()
    var dayDiff = 7 - now.getDay();
    var startOfNextWeek = new Date(now.valueOf());
    startOfNextWeek.setDate(now.getDate() + dayDiff);
    startOfNextWeek.setHours(0);
    startOfNextWeek.setMinutes(0);
    startOfNextWeek.setSeconds(0);
    return Math.floor((startOfNextWeek - now) / 1000);
}

console.log('Seconds remaining to next week start: ' + distranceToNextWeekStartInSeconds())

您可以简单地在计时器内调用此函数来进行实时计算和显示,就是这样。

关于javascript - 下周开始计时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45027977/

相关文章:

php - 如何阻止用户伪造请求?或者如何检测虚假请求?

javascript - JS 异步并等待在 Internet Explorer 中工作

javascript - 仅捕获链接上的左键单击

javascript - 如何在 RxJS 中通过点击流从一个流遍历数组?

java - 定时器无法正常工作(Java)

javascript - 如何在 JavaScript 中更改计时器上交通灯的灯?

java - 每天在特定时间之间每 15 分钟运行一次方法

javascript - 什么时候调用 "DOMNodeInserted"事件?

java - 安排给定时间的工作

c# - 如果中间发生另一个事件,调度程序计时器如何在滴答事件中执行其工作?这段代码有什么问题?