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");
}
};