Skip to content
Advertisement

setInterval keeps on running after clearInterval called

This is a snippet of the code:

var interval3 = null;

React.useEffect(() => {
    if(running) {
    if(interval3) clearInterval(interval3);    
    interval3 = setInterval(() => {
         console.log('running')
      }, 1000);}
      else {
        clearInterval(interval3)
      }  
    
}, [running]);

I checked the solutions suggested in other posts but none of them is working.

Advertisement

Answer

You can use state value to track and keep id of interval. Check below for detail.

  const [id, setId] = useState(null);

  useEffect(() => {
    if (running) {
      if (id) return;
      const intervalId = setInterval(() => {
        console.log('running');
      }, 1000);
      setId(intervalId)
    } else {
      setId(null);
      clearInterval(id);
    }
  }, [running, id]);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement