I have a stopwatch that has buttons to start, stop, and reset the time. I assigned an interval to a variable to pause it using clearInterval every time I click the stop button, but my interval is calling the function even though I clicked no button. How do I fix this?
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const resetButton = document.getElementById('reset');
const myInterval = setInterval(setTime, 10);
startButton.addEventListener('click', () => {
setInterval(setTime, 10);
})
stopButton.addEventListener('click', ()=> {
clearInterval(myInterval);
})
const timeUnits = ['00', '00', '00', '00'];
milliSeconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
function setTime() {
if (minutes == 60) {
hours++;
minutes = 0;
timeUnits[0] = hours;
timeUnits[1] = 0;
} else if (seconds == 60) {
minutes++;
seconds = 0;
timeUnits[1] = minutes;
timeUnits[3] = 0;
} else if (milliSeconds == 100) {
seconds++;
milliSeconds = 0;
timeUnits[2] = seconds
timeUnits[3] = 0;
document.getElementById('para').innerHTML = timeUnits.join(':');
} else {
milliSeconds++;
timeUnits[3] = milliSeconds;
document.getElementById('para').innerHTML = timeUnits.join(':');
};
}
<p id="para">00:00:00:00</p>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>