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

208
Visualizações
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 Respostas
Responde à pergunta

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 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