Skip to content

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.

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