Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!