Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
Why Does clearInterval only works the first time?

This is my code below:

function triggerTimer() {
    var myInt = window.setInterval(timerStart, 1000);
    setTimeout(removeInt, 4000);
}
function timerStart() {
    var timerValue = parseInt(document.getElementById('timer').innerHTML);
    if (timerValue > 0) {
        timerValue -= 1;
        document.getElementById('timer').innerHTML = '0' +timerValue.toString();
        console.log(timerValue);

    }
    else {
        var correct = document.getElementById(`c${row}`).innerHTML;
        multiplechoice.innerHTML = '<p>The correct answer is <span style="color: white;" id=`c${row}`>'+correct+'</span><br><button onclick="submitEntry();">Next Question</button></p>';
    }
}
function removeInt() {
    if(clearInterval(myInt)) {console.log('success')} else {console.log('fail')}
}

Above this code is a timer that decreases every time timerStart function is called. The problem is that the timer stops the first time removeInt function is triggered, even though it logs 'fail'.

But the second time timerStart is triggered, the time still decreases, but when removeInt is called, the interval isn't cleared.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are getting failed logged because clearInterval returns undefined even when it is successful.

So your removeInt function,

if(clearInterval(myInt)) {console.log('success')} else {console.log('fail')}

is getting evaluated like this,

if(undefined) {console.log('success')} else {console.log('fail')}

Here's a doc about clearInterval for more info, https://developer.mozilla.org/en-US/docs/Web/API/clearInterval

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda