Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
¿Cómo finalizar mi temporizador de cuenta regresiva cuando se hace clic en un botón?

Estoy tratando de crear una función que finalice un temporizador de cuenta regresiva , o que automáticamente haga que los minutos y segundos formen parte del countdown timer === 0 ; sin embargo, ¡parece que usar clearInterval(time) no funciona! ¿Alguien podría señalar cómo podría lograr lo que estoy tratando de hacer?

Tenga en cuenta que he hecho los minutos startingMinutes = 1 solo para mi comodidad.

A continuación se muestra la función de cuenta regresiva y HTML:

 // FUNCTION - countDown function that counts down from 8 minutes const startingMinutes = 1; let time = startingMinutes * 60; function updateCountDown() { const minutes = Math.floor(time / 60); let seconds = time % 60; seconds = seconds < 1 ? '0' + seconds : seconds; document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`; time--; time = time < 0 ? 0 : time; if (minutes == 0 && seconds == 0) { document.getElementById('tableStyle').style.display = "block"; document.getElementById('wordsIncluded').style.display = "block"; document.getElementById('show_header_one').style.display = "block"; recognition.abort(); //speech recognition stops when countdown timer ends isListening = false; } //my attempt at clearing the countdowntimer! window.addEventListener('DOMContentLoaded', function() { document.getElementById("submit_button").addEventListener("click", function() { clearInterval(time); })});

HTML:

 //where the countdown timer is displayed <div id="circle"><p id="countdown">8:00</p></div> //Click the below button and the countdown timer will end (minutes === 0 and seconds === 0) <button id="submit_button" type="submit">Click to Submit</button>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Para usar clearInterval , debe pasarle el valor devuelto por setInterval

Tengo un ejemplo a continuación usando su código, donde paso el valor de "setInterval" al que llamo "intervalo" a una función "stop" que llama a "clearInterval" para detener el temporizador y ejecuta el código que estaba ejecutando.

 let isListening = true; const recognition = { abort: () => console.log('aborted') }; function updateCountDown(time) { const minutes = Math.floor(time / 60); const seconds = time % 60; const timer = document.getElementById("countdown"); timer.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`; } function start(time) { const interval = setInterval(() => { if (--time) updateCountDown(time); else stop(interval); }, 1000); document.getElementById("submit_button") .addEventListener("click", () => stop(interval)) } function stop(interval) { updateCountDown(0); // This line sets time to 0 clearInterval(interval); foo() } // I assume you want this to happen when the timer runs down or the button is clicked function foo() { document.getElementById('tableStyle').style.display = "block"; document.getElementById('wordsIncluded').style.display = "block"; document.getElementById('show_header_one').style.display = "block"; recognition.abort(); //speech recognition stops when countdown timer ends isListening = false; } start(8*60)
 #tableStyle, #wordsIncluded, #show_header_one { display: none; }
 <p id="tableStyle">Table Style</p> <p id="wordsIncluded">Words Included</p> <p id="show_header_one">Show Header One</p> <div id="circle"> <p id="countdown">8:00</p> </div> <button id="submit_button" type="submit">Click to Submit</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

const startingMinutes = 1; let time = startingMinutes * 60; var abort_count_down = true; function updateCountDown() { if (abort_count_down) { const minutes = Math.floor(time / 60); let seconds = time % 60; seconds = seconds < 1 ? '0' + seconds : seconds; document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`; time--; time = time < 0 ? 0 : time; if (minutes == 0 && seconds == 0) { document.getElementById('tableStyle').style.display = "block"; document.getElementById('wordsIncluded').style.display = "block"; document.getElementById('show_header_one').style.display = "block"; recognition.abort(); //speech recognition stops when countdown timer ends isListening = false; } }; //my attempt at clearing the countdowntimer! window.addEventListener('DOMContentLoaded', function() { document.getElementById("submit_button").addEventListener("click", function() { abort_count_down = false; })});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda