in the title I used a clock as an example but my question is for all functions.
How do I stop some function when it is not on-screen. For the clock I used the useEffect
Hook with setInterval()
, since I am using ReactJs. So how do I stop the interval when the page is not visible on the screen so it does not slow down the users computer. I read that it is not possible to stop setInterval so I know that I need to clearInterval
and and setInterval
again.
Asked
Active
Viewed 33 times
0

Allleex
- 137
- 9
-
Simply return a cleanup function in ```useEffect``` which clears the interval using ```clearInterval```, so that whenever the component unmounts, the functionality in ```useEffect``` stop working. – Yash Sharma Jan 14 '22 at 12:53
-
@YashSharma , I know but this, but when I switch the tab or got to another screen, doesn't unmount the component. It is still mounted. – Allleex Jan 14 '22 at 13:42
-
By another screen, you mean another page? – Yash Sharma Jan 15 '22 at 05:30
-
does not matter. When the cursor is not on the page of the clock. – Allleex Jan 15 '22 at 22:10