11

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);
Guru
  • 621
  • 1
  • 6
  • 15

3 Answers3

3

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?

SagarScript
  • 1,145
  • 11
  • 15
1

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.

ICW
  • 4,875
  • 5
  • 27
  • 33
1

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

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31364648) – MAXE Mar 30 '22 at 10:29