0

What I'd like to happen here is to display a random number every 50ms and then stop after 5 seconds, creating an effect of animated random numbers. Then compare the last random number generated to the input number by the user. If the last random number generated is equal to the input of the user then it will do something like console.log

The problem here is the code doesn't do something even if the last random number generated is equal to the input of the user.

What's the best way to generate random number animation in reactjs and compare the random number to an input number? (like using an if statement that compares if the random number is equal to the input number)

  const [randomNumber, setRandomNumber] = useState(0);
  const [toggle, setToggle] = useState(false);

  const [inputNum, setInputNum] = useState(0);

  useEffect(() => {
    let counter;
    if (toggle) {
      counter = setInterval(
        () => setRandomNumber(Math.floor(Math.random() * 10)),
        50
      );
    }
    return () => {
      clearInterval(counter);
    };
  }, [toggle]);

  const handleGenerateNumber = () => {

    setToggle(true);
    setTimeout(() => {
    setToggle(false);
    
    }, 5000);

    if (inputNum === randomNumber) {
      console.log(randomNumber, "you won");
    }
  };
Noam Yizraeli
  • 4,446
  • 18
  • 35
John
  • 1
  • 1

1 Answers1

0

You have mistake in if statement. It must be in setTimeout block. Demo: https://codesandbox.io/s/dreamy-booth-ddtni

Vitaliy Rayets
  • 2,299
  • 1
  • 6
  • 12
  • It's not working properly. The input is not being compared to the current random number generated. The inputNum is being compared to the random number generated before clicking start again – John Sep 17 '21 at 15:14
  • @John https://stackoverflow.com/questions/55198517/react-usestate-why-settimeout-function-does-not-have-latest-state-value – NeERAJ TK Sep 17 '21 at 15:17
  • Yup, state from useState hook inside a setTimeout is not updated. Solution is use case useRef instead of useState. Demo updated https://codesandbox.io/s/dreamy-booth-ddtni – Vitaliy Rayets Sep 21 '21 at 09:06