I made a count down timer and the start button starts the count with a setInterval. My problem is that if a user accidently clicks on the start button again, it starts another interval and speeds up the count down.
const timeH = document.querySelector("h1");
let timeSecond = prompt("Enter minutes here") * 60;
displayTime(timeSecond);
function displayTime(second) {
const min = Math.floor(second / 60);
const sec = Math.floor(second % 60);
timeH.innerHTML = `${min < 10 ? "0" : ""}${min}:${sec < 10 ? "0" : ""}${sec}`;
}
function endTime() {
timeH.innerHTML = "TIME OUT";
}
function countDown() {
timeSecond--;
displayTime(timeSecond);
if (timeSecond <= 0 || timeSecond < 1) {
endTime();
}
}
document.querySelector(".start").addEventListener("click", () => {
count = setInterval(countDown, 1000);
});
document.querySelector(".stop").addEventListener("click", () => {
clearInterval(count);
});
document.querySelector(".reset").addEventListener("click", () => {
clearInterval(count);
timeSecond = prompt("Enter minutes here") * 60;
displayTime(timeSecond);
});
Change
document.querySelector(".start").addEventListener("click", () => {
count = setInterval(countDown, 1000);
});
document.querySelector(".stop").addEventListener("click", () => {
clearInterval(count);
});
document.querySelector(".reset").addEventListener("click", () => {
clearInterval(count);
timeSecond = prompt("Enter minutes here") * 60;
displayTime(timeSecond);
});
to
let startButton = document.querySelector(".start");
let stopButton = document.querySelector(".stop");
startButton.addEventListener("click", () => {
count = setInterval(countDown, 1000);
startButton.disabled = true;
});
stopButton.addEventListener("click", () => {
clearInterval(count);
startButton.disabled = false;
});
document.querySelector(".reset").addEventListener("click", () => {
clearInterval(count);
startButton.disabled = false;
timeSecond = prompt("Enter minutes here") * 60;
displayTime(timeSecond);
});
The disabled property disables the button when it is set to true.
You can read more on that property on MDN: https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement/disabled
So add a check that it is running
document.querySelector(".start").addEventListener("click", () => {
if (count) return;
count = setInterval(countDown, 1000);
});
function stopTimer() {
if (!count) return;
clearInterval(count);
count = null;
}
document.querySelector(".stop").addEventListener("click", stopTimer);
document.querySelector(".reset").addEventListener("click", () => {
stopTimer();
timeSecond = prompt("Enter minutes here") * 60;
displayTime(timeSecond);
});