Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 604
Guru Avatar asked Aug 24 '18 05:08

Guru


People also ask

Does setInterval run in background React Native?

The callback passed too setInterval will run even while the app is backgrounded. Then minimize your app.

Does setTimeout work in the background React Native?

In React Native, when setTimeout is used to schedule execution of callback and then app is backgrounded, callback is never executed.

How do I turn off background timer in React Native?

There can be used only one background timer to keep code consistent. BackgroundTimer. runBackgroundTimer(() => { //code that will be called every 3 seconds }, 3000); //rest of code will be performing for iOS on background too BackgroundTimer. stopBackgroundTimer(); //after this call all code on background stop run.

Can I use setInterval in useEffect?

A pretty straightforward functional component that holds a state in counter . The state is incremented every second thanks to the setInterval defined in the useEffect .


1 Answers

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?

like image 87
Sagar Patel Avatar answered Sep 27 '22 18:09

Sagar Patel