0

Im having a problem with my function, after the page is change, the function keeps running and I got error, how can I stop it, thanks

 componentDidMount() {
    var current = 0;
    var slides = document.getElementsByClassName("j1");

    setInterval(function() {
          let rec = window.location.href;
          rec = rec.split('/');
          console.log(rec);

          for (var i = 0; i < slides.length; i++) {
            slides[i].style.opacity = 0;
            for (var j = 0; j < 10000; j++) {
              let k = j;
            }

          }
          current = (current != slides.length - 1) ? current + 1 : 0;
          slides[current].style.opacity = 1;

    }, 5000);
    } 
chazsolo
  • 7,873
  • 1
  • 20
  • 44
Jader Costa
  • 307
  • 3
  • 16
  • slides[current].style.opacity = 1 error, because it doesnt exist in others page – Jader Costa Oct 22 '18 at 18:46
  • Possible duplicate of [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – Herohtar Oct 22 '18 at 19:00

1 Answers1

3

You have to unregister your interval. Something like this:

class Example extends React.Component {
  componentDidMount() {
    this.timer = window.setInterval(function() {
      ....
    }, 5000);
  }

  componentWillUnmount() {
    window.clearInterval(this.timer);
  }
}
Alserda
  • 4,246
  • 1
  • 17
  • 25
  • Good to hear! Mark my reply as the answering question to prevent other people from reviewing this. Have a good day! – Alserda Oct 22 '18 at 18:52