boterop / react-native-background-timer

Emit event periodically (even when app is in the background)
https://www.npmjs.com/package/@boterop/react-native-background-timer
MIT License
5 stars 1 forks source link

Can I clear the queue of callbacks? #12

Closed James-Clark12 closed 2 months ago

James-Clark12 commented 4 months ago

Hey, thank you for taking the time to fork and improve the react-native-background-timer library I am finding it very useful.

One issue I am having is that my callback functions often end up delayed in a long queue and continue to be executed long after my component has unmounted.

    useEffect(() => {
        BackgroundTimer.runBackgroundTimer(backgroundTimerCallback, 1000);
        return () => {
            BackgroundTimer.stopBackgroundTimer();
        };
    }, [backgroundTimerCallback]);

This is my code. Basically for the duration of this component being mounted I want it to run this callback every second whilst in the background. This works, however, even after the app is again in the foreground and this component has been unmounted I still have the callback functions being executed. Suppose my app was in the background for 1 minute, once back in the foreground I will see the callback being triggere/ executed every second for another 30 seconds.

Is there any way for me to clear the queue of callbacks that have built up whilst this backgroundTimer has been running.

Thanks you for any help and thank you again for this library.

boterop commented 2 months ago

I'm not sure about what are u trying to do. but... Perhaps stopping the timer when the app is in the foreground? something like

useEffect(() => {
    if(state == "active") BackgroundTimer.stopBackgroundTimer();
    BackgroundTimer.runBackgroundTimer(backgroundTimerCallback, 1000);
    return () => {
        BackgroundTimer.stopBackgroundTimer();
    };
}, [backgroundTimerCallback]);

useEffect(() => {
    const handleChange = AppState.addEventListener("change", changedState => {
        setState(changedState);
    });

    return () => {
        handleChange.remove();
    };
}, []);

https://www.geeksforgeeks.org/how-to-check-app-state-in-react-native/