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

205
Visualizações
ClearInterval doesn't work, the following setInterval restart with 2x speed

I have a simple slideShow on witch i want a "pause" and "play" function, with onClick, using setInterval and clearInterval. The first setInterval works good. The following clearInterval create a pause in the loop, but don't reset intervalId, so, the next setInterval is running to fast. I saw some post about this problem here, but they doesn't solve mine. If someone can help me, it will be great !

let i = 0;
var elements = document.querySelectorAll('.mes_elements');

function ma_fonction(){ 
    elements[i].style.opacity = 1;
    for(let j = 0; j < elements.length; j++){  
        if(j!=i){  
            elements[j].style.opacity = 0;
        }
    }
    i++;
    if(i == elements.length){ i = 0; }
}

var lecture = true;
var intervalId = setInterval(ma_fonction, 1500);

document.querySelector('.ma_div').addEventListener('click', function() {
    if(lecture == true){
        clearInterval(intervalId);
        // window.clearInterval(intervalId);  doesn't work to
        lecture = false;
    }else{ 
        setInterval(ma_fonction, 1500);
        // window.setInterval(ma_fonction, 1500);   doesn't work to
        lecture = true;
    } 
});
.mes_elements {
   padding:1em;
   background:blue;
   margin: 1em;
}
<div class="ma_div">
        <div class="mes_elements"></div>
        <div class="mes_elements"></div>
        <div class="mes_elements"></div>
</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In your code here

 }else{ 
        setInterval(ma_fonction, 1500);
        // window.setInterval(ma_fonction, 1500);   doesn't work to
        lecture = true;
    } 

You're not setting intervalId to the new setTimeout so you only ever clear the first one and then an empty var.

Change it to

 }else{ 
        intervalId = setInterval(ma_fonction, 1500);
        // window.setInterval(ma_fonction, 1500);   doesn't work to
        lecture = true;
    } 
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