0

I was following along an MDN article and came up with this code for a working stopwatch. I can imagine that it sucks—–for one thing, using setTimeout with 1000ms isn't exactly 1000ms (it seems to be + or - 2 or 3 ms, maybe more). The other thing is that I'm not sure if the way I'm handling the stop button (actually a pause button) is ideal. I'd be happy to hear your thoughts on how to improve this code bearing in mind the fact that I'm pretty new to JS so it would be nice if you could explain your points in detail.

const start = document.querySelector("#start");
const stop = document.querySelector("#stop");
const reset = document.querySelector("#reset");
const clock = document.querySelector("#clock");
let timeCounter = 0;
let startTime;
let stopTime = 0;
let intervalID;
clock.textContent = "0";

start.addEventListener("click", startTimer);
stop.addEventListener("click", stopTimer);
reset.addEventListener("click", resetTimer);

function startTimer() {
  if (stopTime === 0) {
    startTime = Date.now();
  } else {
    startTime = Date.now() - (stopTime * 1000);
  }
  intervalID = setInterval(calcElapsedTime, 1000);
}

function calcElapsedTime() {
  let timeElapsed = Math.floor((Date.now() - startTime) / 1000);
  clock.textContent = timeElapsed;
}

function stopTimer() {
  stopTime = clock.textContent;
  clearInterval(intervalID);
}

function resetTimer() {
  clearInterval(intervalID);
  clock.textContent = "0";
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I made you a snippet. Please add relevant HTML and CSS to it – mplungjan Jan 09 '21 at 07:09
  • Please visit [help], take [tour] to see what and [ask]. ***[Do some research](https://www.google.com/search?q=javascript+stopwatch+precision+site:stackoverflow.com)***, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) - however your question is better asked at code review than here – mplungjan Jan 09 '21 at 07:10

0 Answers0