【问题标题】:Restart counter every week每周重新启动计数器
【发布时间】:2021-01-29 19:23:25
【问题描述】:

我想创建一个每周重置的计数器,我发现一个或多或少有效的代码,但是当它变为 0 时,它显示为负数.... -1d -1h -2m -5s

            <script>
            // Set the date we're counting down to
            var countDownDate = new Date("Jan 29, 2021 20:21:0").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);

            // 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) {
                //document.getElementById("demo").innerHTML = "GAME DAY";
                if(distance < - 1000 * 60 * 60* 24){ // if its past the "game day"
                    // reset timer to next week
                    countDownDate += 1000 * 60 * 60 * 24 * 7
                }
            }
        }, 1000);
      </script>
      <span id="demo"></span>

【问题讨论】:

  • 这个计数器应该从什么时候到什么时候倒计时?如果您希望计数器每周重置,为什么要硬编码Jan 29, 2021 20:21:0?距离
  • 我只是在测试,我想数一下,从周五到周五
  • 您希望它从每周五晚上 8:21 开始倒计时,并以 h:m:s 显示到下周五晚上 8:21 的剩余时间?
  • 正确,正好是8:00,每周五,到0的时候,重新开始计数,直到下周五
  • 好的,感谢您的澄清。您希望何时显示“比赛日”?我猜晚上 8 点后的一两个小时应该会显示这个(游戏是实时的)还是应该立即开始下周的倒计时?

标签: javascript html counter


【解决方案1】:

您需要根据当前日期计算下一个日期,而不是对日期进行硬编码。

类似这样,不过最好将幻数(520)移动到变量中。

let getNextGameDayTime = function() {
  let now = new Date();
  let dayOfTheWeek = now.getDay();
  let dayOffset = 5 - dayOfTheWeek; // Friday is the 5th day of the week
  if (dayOffset < 0 || (dayOffset === 0 && now.getHours() > 20)) {
   dayOffset += 7;
  }
  let result = new Date();
  result.setDate(result.getDate() + dayOffset);
  result.setHours(20);
  result.setMinutes(0);
  result.setSeconds(0);
  result.setMilliseconds(0);
  return result;
}

console.log(getNextGameDayTime());

至于倒计时结束后一小时内不显示消息,您可以使用由此产生的距离。

【讨论】:

  • 看起来很棒!但是我怎样才能将它添加到我的 html 中,而不是 console.log?
  • 这只是计算countDownDate的代码。您的其余代码应该仍然可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2019-10-30
相关资源
最近更新 更多