can i make 2 timers run in sync ?in react native

Viewed 152

I have a timer1 which runs in background when app is killed/background/foreground and another timer2 which runs only in foreground.

now whenever app state changes from killed -> foreground I want timer2(forground) to match timer1(killed) time interval and continue..

for ex:-

//timer1
setInterval(() => {
    console.log("in killed state");
}, 30000)

//timer2
setInterval(() => {
    console.log("in foreground state");
}, 30000)

when app is brought back to foreground I want both timers to sync together and timer2 to match timer1 so both consoles are printed together.

can such a thing be done? a slight small delay is also fine.

1 Answers

You can achieve this behavior with a single timer by checking if the app is in the foreground state.

let foreground = true //keep track of the foreground state here

setInterval(()=>{
console.log("in killed state");
if (foreground) console.log("in foreground state");
},30000)
Related