【问题标题】:Countdown Timer every 15-Minutes in the hour倒数计时器每 15 分钟一小时
【发布时间】:2022-09-30 17:28:57
【问题描述】:

我有一个网络研讨会,每天每小时每 15 分钟运行一次(例如:11:00、11:15、11:30 和 11:45)。

我想要一个倒计时计时器,它显示距离下一次开始时间的剩余分钟数,我可以从几天的搜索中找到,并试图自己弄清楚这一点是每小时倒计时。

我的问题是,如何每 15 分钟而不是每 60 分钟更新一次此代码。

<script>
/* Return minutes and seconds to next hour
** @returns {Object} minutes: minutes remaining
**                   seconds: seconds remaining
*/
function getTimeRemaining() {
  var t = Date.now();
  var seconds = (60 - Math.floor(t % 6e4 / 1e3)) % 60;
  var minutes = 60 - Math.ceil(t % 3.6e6 / 6e4) + (seconds? 0:1);
  return {
    \'minutes\': (\'0\' + minutes).slice(-2),
    \'seconds\': (\'0\' + seconds).slice(-2)      };
}

// Simple show remaining function
function showRemaining() {
  var r = getTimeRemaining();
  document.getElementById(\'clock\').textContent = (r.minutes + \':\' + (\'0\' + r.seconds).slice(-2));
  // Run again just after next full second
  setTimeout(showRemaining, 1020 - (Date.now() % 1000));
}

showRemaining();
</script>

    标签: javascript countdown countdowntimer


    【解决方案1】:

    该解决方案似乎过于复杂,您绝对应该将setInterval 用于必须每x 秒更新一次内容的任务,递归调用setTimeout 是个坏主意。这是一个更容易理解的解决方案:

    const runEvery = 15 * 60; // 15 minutes in seconds
    
    const showRemaining = () => {
      // get current time in seconds and find when the next run starts in seconds
      const seconds = Math.round(Date.now() / 1000);
      const nextRun = runEvery * Math.ceil(seconds / runEvery);
    
      const timeLeft = nextRun - seconds;
    
      const minutesLeft = Math.floor(timeLeft / 60);
      const secondsLeft = timeLeft % 60;
    
      document.getElementById('clock').textContent = minutesLeft + ':' + ('0' + secondsLeft).slice(-2);
    }
    
    showRemaining();
    setInterval(showRemaining, 1000);
    &lt;div id="clock"&gt;&lt;/div&gt;

    【讨论】:

    • 太好了,非常感谢你解决了我的头痛。
    【解决方案2】:

    你知道如何让计时器每 6 小时更改一次,例如 00:00、06:00、12:00 和 18:00?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      相关资源
      最近更新 更多