Reputation: 45
I'm writing an incremental-style game in React and I have this setInterval inside App.ts:
useEffect(() => {
const loop = setInterval(() => {
if (runStatus) {
setTime(time + 1);
}
}, rate);
return () => clearInterval(loop);
});
I've also got various event handlers along the lines of:
<button onClick={() => increment(counter + 1)}>Increment</button>
Unfortunately, if I click that button multiple times in a second, it will block the setInterval from updating the time
state.
This state using the hooks as well as Redux stored state.
How can I, at the very least, make my setInterval tick reliably, so that I can click around the page without blocking it?
Upvotes: 0
Views: 58
Reputation: 19532
Do it like that
[]
empty dependency means only execute when a component will mount.
useEffect(() => {
const loop = setInterval(() => {
if (runStatus) {
setTime(prev => prev + 1);
}
}, rate);
return () => clearInterval(loop);
}, []); <--- add that []
Notes
runStatus
or rate
variable as a dependency if its dynamic stateUpvotes: 2