setInterval is becoming faster when app is killed then relaunched in react native expo

47 views Asked by At

I am building a stopwatch in react native expo which has the ability to run in the background or when the app is killed by using asyncstorage. When I start the stopwatch then I kill the app then relaunch it in the expo go or after installing the app on my real device, the stopwatch becomes faster than it should be. I have searched on google for solutions, they suggested to clear the interval when the app is unmounted but how can I do it when I have a start and stop button that starts the interval. Below is the code that is related to this section. (If anything else needed to be shared please let me know)

To Note: When I kill the app then relaunch it, I see the timer going faster. If I click stop, then start, the timer will work properly and not fast so it is a matter of clearInterval but where to use is the question.

const [isRunning, setIsRunning] = useState(false);
const [time, setTime] = useState(0);


const intervalRef = useRef(null);

const handleStartButtonPress = async () => {
    setIsRunning(!isRunning);
};

useEffect(() => {
    console.log("started: ", started);
    
    if (isRunning) {
        intervalRef.current = setInterval(() => {
            setTime(previousTime => previousTime + 100);
        }, 100);
    } else {
        clearInterval(intervalRef.current);
    }

    return () => clearInterval(intervalRef.current);
    
}, [isRunning]);
0

There are 0 answers