Hice un temporizador de cuenta regresiva y el botón de inicio inicia la cuenta con un setInterval. Mi problema es que si un usuario vuelve a hacer clic accidentalmente en el botón de inicio, comienza otro intervalo y acelera la cuenta regresiva.
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); });Cambio
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); });a
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); }); La propiedad disabled desactiva el botón cuando se establece en true . Puede leer más sobre esa propiedad en MDN: https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement/disabled
Así que agrega una verificación de que se está ejecutando
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); });