Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda