I want to make an algorithm that every time you log into the page to start a 5 minute counter and while this 5 minute counter is going in I want to make some actions every minute for example.
I tried starting a setTimeout with useEffect and also setting a flag value to know when the 5 minutes are over:
const [initialTime, setInitialTime] = useState(true)
useEffect(() => {
console.log('starting counter');
setTimeout(() => {
setInitialTime(false)
console.log('changing the time' + " - " + initialTime);
}, 5000);
}, [])
and under it I added the setInterval function which I want to go off only whenever the flag above (initialTime is true) otherwise not.
useEffect(() => {
setInterval(() => {
if (initialTime) {
//some action
}
}, 1000);
}, [])
In my head that should work, but setInterval reacts really strange, it doesn't detect the state changes, this is an example log if I place the setTimeout to 5 seconds and setInterval to 1 second:
true
true
true
true
changing the time - true
true
and then it continues, the setTimeout doesn't even change the state in this case, but even if it does, setInterval doesn't detect it and it still goes through. I need help completing the algorithm.