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);
The callback passed too setInterval will run even while the app is backgrounded. Then minimize your app.
In React Native, when setTimeout is used to schedule execution of callback and then app is backgrounded, callback is never executed.
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.
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 .
This is expected behaviour - when the application pauses, so do all setInterval
's running and (and setTimeout
s 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With