Skip to content
Advertisement

Recurring Countdown Timer – Every 10 Minutes Based On Actual Time

I am trying to create a countdown timer that will continually count down to the nearest 10 minute interval of real time. So if a user lands on the page at 4:01pm it would count down 9:00 and then reset when it hits 0. But the time would always be relative to actual time.

This is what I have so far:

    <p id="timer"></p>

    <script>
      var start = Date.now(),
        r = document.getElementById("timer");
      (function f() {
        var diff = Date.now() - start,
          ns = ((6e5 - diff) / 1000) >> 0,
          m = (ns / 60) >> 0,
          s = ns - m * 60;
        r.textContent =
          m + ":" + (("" + s).length > 1 ? "" : "0") + s + " minutes";
        if (diff > 6e5) {
          start = Date.now();
        }
        setTimeout(f, 1000);
      })();
    </script>

Here is a codepen of my code working https://codepen.io/gvolkerding/pen/jOOmygQ

This only counts down 10 minutes from the time that the user lands on the page, but I can’t figure out how to modify it to look for the next 10 minute mark and then count down to it. Any help would be greatly appreciated

Advertisement

Answer

Not the most efficient way to handle this, but it should ensure that the countdown stays consistent with the client machine clock. Just get the minutes and seconds of the current datetime and then calculate the remainder up to the next 10 minute mark.

const timer = document.getElementById('timer');
const countdown = () => {
  const dt = new Date();
  let m = dt.getMinutes();
  let s = dt.getSeconds();
  
  // minutes remaining until next 10 minute mark
  m = s ? 9 - (m % 10) : 10 - (m % 10);
  
  // seconds remaining until next minute mark
  if (s) {
    s = 60 - s;
  }

  timer.textContent = `${m}:${s < 10 ? '0' + s : s} minutes`;
};

setInterval(countdown, 1000);
<p id="timer"></p>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement