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";
}