0

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?

1
  • 1
    try putting [] as your dependency for useEffect. Otherwise every time your state changes, your generating a new interval. Commented Dec 17, 2020 at 20:44

1 Answer 1

2

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

  1. adding time as a dependency will create an infinite loop
  2. you need to add runStatus or rate variable as a dependency if its dynamic state
Sign up to request clarification or add additional context in comments.

10 Comments

This runs on every re-render. Is this desired?
Your IIFE and async are not doing anything useful here, just the [] is all you need..
@Keith got it, I will remove it
Fantastic, that did it for me. Thanks a bunch @Nishargshah + the rest :)
What if runStatus or rate change? Presumably they can otherwise they would be hard coded. They should be included in the dependency array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.