Así que creé un sitio web que eventualmente será un juego para un proyecto personal y he estado trabajando en mi botón de inicio y parada para un temporizador de cuenta regresiva. Mi botón de inicio funciona y cuenta regresivamente perfectamente, pero mi botón de parada no detiene mi temporizador de cuenta regresiva como se supone que debe hacerlo.
Estas son mis funciones de JavaScript para los botones de inicio y parada del temporizador.
function countDown(){ var currTime = 55 var timedown = setInterval(function() { currTime = currTime - 1; document.getElementById("countdowntimer").innerHTML ="The time is:" + currTime; if(currTime == 0){ clearInterval(timedown); document.getElementById("countdowntimer").innerHTML = "BLASTOFF!" } else if(currTime < 25){ document.getElementById("countdowntimer").innerHTML = "Half way to launch " + currTime; } //this is my count down timer function }, 1000);} function stopCount() { for (var i = 0; i < countDown.length; i++) { clearInterval(countDown[i]); }}
//this is supposed to be my stop count function that isn't workingy luego esta es la parte del archivo HTML donde los estoy llamando. Mi botón de inicio funciona pero mi parada no
<button id="stopTime" onclick = stopCount() >Stop!</button>//stop Timer button <button onclick=countDown()>Start Countdown!</button> //Start timer buttonNo sé qué estoy haciendo mal aquí, pero simplemente no puedo hacer que funcione.
El intervalo no está en el ámbito de un lugar donde stopCount() pueda acceder a él. Este es un ejemplo de trabajo. He acortado el tiempo de prueba.
var timedown function countDown(){ var currTime = 4 timedown = setInterval(function() { currTime = currTime - 1; document.getElementById("countdowntimer").innerHTML ="The time is:" + currTime; if(currTime == 0){ clearInterval(timedown); document.getElementById("countdowntimer").innerHTML = "BLASTOFF!" } else if(currTime <= 2){ document.getElementById("countdowntimer").innerHTML = "Half way to launch " + currTime; } }, 1000);} function stopCount() { clearInterval(timedown) } <button id="stopTime" onclick ='stopCount()' >Stop!</button> <button onclick='countDown()'>Start Countdown!</button> <div id='countdowntimer'>timedown is now scoped globally and is accessable by the stopCount function</div>