Search code examples
javascripttimer

How do I fix this this timer?


I am coding a timer and I can pause it and start it again but every time I click start it starts to get faster for each click. Is there any way I can fix this?

I need it to just start and stop with no side affects and no speeding up. It's super simple but I can't figure it out.

let seconds = 0
let decisecond = 0
let centisecond = 0
let millisecond = 0
let timerStarted = false

function start() {
  timerStarted = false
  setInterval(startmillisecond, 10)
}

function startmillisecond() {
  if (!timerStarted) {
    millisecond++
    if (millisecond === 10) {
      millisecond -= 10
      centisecond++
    }
    if (centisecond === 10) {
      centisecond -= 10
      decisecond++
    }
    document.getElementById("timer").innerHTML = decisecond + '.' + centisecond + millisecond
  }
}

function pause() {
  timerStarted = true
}
td {
  border: 1px solid black;
  height: 50px;
  width: 500px;
}
<table>
  <td align="center">
    <h1 id="timer">0.00</h1>
  </td>
  <button onclick="start()">Start</button>
  <button onclick="pause()">Pause</button>
</table>


Solution

  • You are calling setInterval() without clearing the previous interval, causing multiple intervals to run concurrently, making the timer appear to speed up with each start click. You need to clear the previous interval before starting a new one.

        let seconds = 0;
        let decisecond = 0;
        let centisecond = 0;
        let millisecond = 0;
        let timerStarted = false;
        let intervalID;
    
        function start() {
          if (!timerStarted) {
            timerStarted = true;
            intervalID = setInterval(startmillisecond, 10);
          }
        }
    
        function startmillisecond() {
          millisecond++;
          if (millisecond === 10) {
            millisecond -= 10;
            centisecond++;
          }
          if (centisecond === 10) {
            centisecond -= 10;
            decisecond++;
          }
          document.getElementById("timer").innerHTML = decisecond + '.' + centisecond + millisecond;
        }
    
        function pause() {
          timerStarted = false;
          clearInterval(intervalID);
        }
        td {
          border: 1px solid black;
          height: 50px;
          width: 500px;
        }
      <table>
        <td align="center">
          <h1 id="timer">0.00</h1>
        </td>
        <button onclick="start()">Start</button>
        <button onclick="pause()">Pause</button>
      </table>