简体   繁体   中英

setInterval is running after the page is change

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);
    } 

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM