React Interval not stopping after Leaving

Mark OE

I have the problem that the interval I am using in useEffect isn't stopping when leaving the component.

The code is:

useEffect(() => {
    const timer = window.setInterval(() => {
      refreshSave();
    }, 3000);
    return () => {
      window.clearInterval(timer);
    };
  }, []);

I am thinking about animating an empty span and then using onAnimationIteration to trigger the save.

Deolu A

You didn't really give us much of a context to work with (e.g. what do you mean by "leave the component"?), so we're kinda shooting in the dark.

However, as a first step, you could try declaring the timer variable globally:

let timer;     // <- put here
useEffect(() => {
    timer = window.setInterval(() => {
      refreshSave();
    }, 3000);
    return () => {
      window.clearInterval(timer);
    };
  }, []);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related