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 !
<div class="ma_div">
<div class="mes_elements"></div>
<div class="mes_elements"></div>
<div class="mes_elements"></div>
</div>
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;
}
});
CodePudding user response:
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;
}