Skip to content

JavaScript countdown timer counting past zero

This might be a really simple thing to ask but I’ve got a JavaScript countdown timer, but I can’t stop it from counting past 0:00. Instead of stopping at this point, it will continue to -1:59 etc.

I’d also like it to play a beeping sound (which can be found here) when the timer reaches zero.

This is the code I’ve got so far:

<div class="stopwatch">
  <div class="circle">
    <div class="time" id="timer"></div>
  </div>
</div>

<script>
  document.getElementById('timer').innerHTML =
    02 + ":" + 30;
  startTimer();

  function startTimer() {
    var presentTime = document.getElementById('timer').innerHTML;
    var timeArray = presentTime.split(/[:]+/);
    var m = timeArray[0];
    var s = checkSecond((timeArray[1] - 1));
    if(s==59){m=m-1}

    document.getElementById('timer').innerHTML =
      m + ":" + s;
    console.log(m)
    setTimeout(startTimer, 1000);
  }

  function checkSecond(sec) {
    if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
    if (sec < 0) {sec = "59"};
    return sec;
  }
</script>

Any help on this would be appreciated.

Answer

To stop the counter when it reaches zero you have to stop calling the startTimer() function. In the following snippet I have implemented a check to do exactly that.

function startTimer() {
    var presentTime = document.getElementById('timer').innerHTML;
    var timeArray = presentTime.split(/[:]+/);
    var m = timeArray[0];
    var s = checkSecond((timeArray[1] - 1));
    if(s==59){m=m-1}

    document.getElementById('timer').innerHTML =
      m + ":" + s;
    console.log(m)
    // Check if the time is 0:00
    if (s == 0 && m == 0) { return };
    setTimeout(startTimer, 1000);
  }