Guru
Guru

Reputation: 631

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);

Upvotes: 12

Views: 19440

Answers (3)

ICW
ICW

Reputation: 5760

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 a lot of unnecessary fetches because it was always fetching every X seconds in the background.

Upvotes: 1

Daniel Hansson
Daniel Hansson

Reputation: 75

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

Upvotes: 2

SagarScript
SagarScript

Reputation: 1242

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?

Upvotes: 3

Related Questions