'React Native setInterval getting paused when app is in background

I am developing a react native app. For one of the task, I need to use javascript setInterval function, but it get's stop when the app is in the background. Can anyone guide me, why it is stopping? Any solution to it?

My Code:

 let startTimer = setInterval(() => {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        this.setState({ remainMin: minutes, remainSec: seconds });
        if (--timer < 0) {
            this.handelTimerStop();
            timer = duration;
            this.setState({ isResend: true });
        }
    }, 1000);


Solution 1:[1]

This is expected behaviour - when the application pauses, so do all setInterval's running and (and setTimeouts pending). You want to look into background tasks, to keep something running while the app is minimised:

This should help you achieve that:

How can I run background tasks in React Native?

Solution 2:[2]

WARNING TO OTHER DEVS

Posting this warning because I the other answers in this thread lead me to believe that "setInterval" callback would stop running whenever the app is minimized.

This is not true, at least for React Native 0.64+ on iOS 15. The callback passed too setInterval will run even while the app is backgrounded.

Try this in your component:

useEffect(()=>{
    setInterval(()=>console.log('It ran'), 1000);
}, []);

Then minimize your app. It will continue logging.

In my case the callback was fetching data from the server. This made my server costs go up 1000x because it was always fetching every X seconds in the background.

Not sure if this changed recently or what.

Solution 3:[3]

setInterval seems to work for iOS (backgrounded) but not for Android.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sagar Patel
Solution 2 ICW
Solution 3 Daniel Hansson