Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda