简体   繁体   中英

The clearInterval() function doesn't clear Interval In React

Im doing this:

startinterval = () => {
    this.interval = setInterval(this.intervalFunction, 10000)
}


clearInterval = () => {
    clearInterval(this.interval)
}

but when i call the clearInterval function it doesn't do anything and the interval continues

If you are using functional components you can use:

function MyComponent() {
  const [intervalId, setIntervalId] = useState();

  useEffect(() => {
    let id = setInterval(() => {
      //Code to do
    }, 10000);
    setIntervalId(id);

    return () => {
      clearInterval(intervalId);
    };
  });

  return <div>UI Here</div>;
}

If you are using a class as component:

class MyComponent {
    intervalId;

  componentDidMount() {
    this.intervalId = setInterval(() => {
        //Code to do here or call another function
    }, 10000);
  }

  componentWillUnmount() {
      clearInterval(this.intervalId);
  }
}

The best important to take in advance is that you need store the id for clear the timeout. If you lost the correct id the clear function won't work correctly.

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