Search code examples
javascripthtmltimercountdown

How to make a 4 hour auto restarting timer?


I need a timer to countdown 4 hours at a time and then restart after hitting 0. The time remaining needs to be the same across all clients. I've currently got this:

function addZero(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}
setInterval(function() {
  function addZero(i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  }
  var d = new Date();
  var s = (d.getSeconds());
  var m = (d.getMinutes());
  var x = document.getElementById("timer");
  var c = addZero(30 - m) + ":" + addZero(60 - s);
  var d = addZero(60 - m) + ":" + addZero(60 - s);
  if (m < 30) {
    t = c
  } else {
    t = d
  }

  x.innerHTML = t;
}, 250)
<div align="center">
  <table>
    <tbody>
      <td style="font-size:15px;">Time to next restart:</td>
      <td style="font-size:16px;" id="timer"></td>
      <td nowrap="nowrap" width="15px">
        <p style="text-align: left;"></p>
      </td>
    </tbody>
  </table>
</div>

Which counts down 30 minutes and then resets back to 30. However when it hits the last second it counts the 60, instead of going to straight to 59 (so 4:00/3:60/3:59). Also it needs to countdown beginning at noon (12pm) EST. I would like the time to display in h:mm:ss format, I'm missing the hour on the above code as well.


Solution

  • Use PHP to get the date/time on initial page load, rather than client/JS Date() - this could be wildly different across machines, so it's worthless if you want clients synchronised (the PHP date will come from the server clock, so provided it's correct, you can sync multiple clients to it). Even taking this time as a base and then counting down four hours on the client is not likely to result in well-synced time - I would refer periodically to the server to sync it up.

    As for your problem with it displaying 60, can you not just replace the figures in your code like so:

    var d = addZero(60 - m) + ":" + addZero(60 - s);
    

    becomes

    var d = addZero(59 - m) + ":" + addZero(59 - s); 
    

    ?

    Seeing as the return values will always be 0-59, this will just reverse it, you won't get a minus figure, it will display what a digital clock actually would (you never see them get to 60 mins/secs, they reset to 0).

    I'd do the minute/second counting with JS, as it's pointless referring to the server so regularly - if, when you do sync, you notice a disrepancy, it's not likely to be too high if you don't leave it a long time (like 4 hours) between checks.

    What is this actually for?