Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

deliberate infinite loop in useEffect keeps running after component unload?

I need to have an infinite loop inside a useEffect for a continual process, however when the component gets unloaded the loop keeps going, I also have issues with the setTimeout cleanup and setTimeout violations in the console .. I have tried to use a cleanup function but to no avail?

  function delay(time) {
    return new Promise((resolve) => setTimeout(resolve, time));
  }

useEffect(() => {
animate();
    const animate = async (dates) => {
      let i = 0;
      await delay(5000);
      while (true) {
        console.log("setting");        
        await delay(1500);
        if (i === dates.length - 1) {
          i = 0;
        } else {
          i++;
        }
      }     
    };
  }, []);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The other answer’s close, but if you want it to run continuously, what you need is setInterval() (1). While also saving its ID to clear it on clean up.

useEffect(() => {
  let interval;
  animate();
  const animate = (dates) => {
    let i = 0;
    interval = setInterval(() => {
      console.log("setting");
      if (i === dates.length - 1) {
        i = 0;
      } else {
        i++;
      }
    }, 1500)    
  };
  return () => clearInterval(interval)
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading