I coded a stopwatch watching tutorials with JS. I commented out a few lines of code that my tutor had written, something that I do not understand. So after I commented those lines out, whenever I click the start button more than once, my stopwatch moves more faster than a normal clock. But when I undo the changes, it moves perfectly. Below is function watchStart()
that I changed.
let [hours, minutes, seconds] = [0, 0, 0];
let displayTime = document.getElementById("displayTime");
let timer = null;
function stopWatch() {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
let h = hours < 10 ? "0" + hours : hours;
let m = minutes < 10 ? "0" + minutes : minutes;
let s = seconds < 10 ? "0" + seconds : seconds;
displayTime.innerHTML = h + ":" + m + ":" + s;
}
function watchStart() {
// if (timer!== null){
// clearInterval(timer);
// }
timer = setInterval(stopWatch, 1000);
}
function watchStop(){
clearInterval(timer);
}
function watchReset(){
clearInterval(timer);
[hours, minutes, seconds] = [0, 0, 0];
displayTime.innerHTML = "00:00:00";
}
<div class="stopwatch">
<h1 id="displayTime">00:00:00</h1>
<div class="buttons">
<button onclick="watchStop()">Stop</button>
<button onclick="watchStart()">Start</button>
<button onclick="watchReset()">Reset</button>
</div>
</div>
I don’t understand why my tutor uses that code on the watchStart()
function. When I commented those lines of code and ran the page on the browser and clicked the start button, I noticed that something wasn’t ok. When I click the start button more than once simultaneously, the clock moves faster than usual. I noticed the problem but I don’t understand how my tutors code solved the problem.
2
Answers
When you click the start button again you add an extra interval with
setInterval()
so yourstopWatch()
runs twice often.You could want to clear the previous timer with already existing function created for that:
But for better UX you could disable the start button while the stopwatch is running.
That section of code clears the existing stopwatch timer, if one exists. When you change the
timer
variable to a different timer, the old one still exists but now you’ve lost track of it, so if you don’t clear it, the old timer will continue updating the stopwatch at the same time as the new one, causing the stopwatch to move twice as fast. You also won’t have a reference to it to be able to stop it later, so your stop and reset buttons won’t stop or reset the old timer.