Pause works incorrectly. How to fix?

I have a code that should implement stopwatch. It works, but if I start stopwatch after pressed pause or reset button, then time is ticking too fast. How can I fix it?

Resolved.

Answer

Here’s a trimmed down example of how one could store an interval id and then use it to clear the interval:

let SECONDS = 0;
let intervalId;

function run() {
  intervalId = setInterval(main, 1000)
}

function pause() {
  clearInterval(intervalId)
}

function reset() {
  clearInterval(intervalId)
  SECONDS = 0
  update_display()
}

function update_display() {
  document.getElementById("seconds").innerText = SECONDS
}

function main() {
  SECONDS++
  update_display()
}
    <div class="display-time">
      <span id="seconds">0</span>
    </div>

    <!-- buttons start, stop and reset -->
    <div class="button-group">
      <button id="btnRun" onclick="run()">RUN</button>
      <button id="btnPause" onclick="pause()">PAUSE</button>
      <button id="btnReset" onclick="reset()">RESET</button>
    </div>

Leave a Reply

Your email address will not be published. Required fields are marked *