Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
What's the best way to generate random number animation in reactjs and compare the random number to an input number?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!