-1

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>
TheBritishAreComing
  • 1,667
  • 2
  • 19
  • 38
Martin
  • 79
  • 1
  • 6
  • 1
    You're not setting var intervalID with the second setInterval. So it clears the first one only. – Kosh Oct 02 '21 at 00:43

1 Answers1

3

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;
    } 
TheBritishAreComing
  • 1,667
  • 2
  • 19
  • 38