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

204
Vistas
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 Respuestas
Responde la pregunta

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