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

129
Visualizações
How to stop execution of a function which is triggered by a button click using another button in ReactJS?

I have a ReactJS app in which a buttonA is running a function onClick and that function has a for loop inside it . I want to break that for loop onclick of another function . the two button's visibilty is controlled using states . whenever we click roll dice btn it will hide itself and show stop bet btn and stop bet btn should onclick stop the execution of runbets function which is declared in onclick of Roll dice . I want the same functionality as Primedice.com .

       const [stopBet, setStopBet] = useState(false);// this is the state declaration for reference
     <button
          type="button"
          className={`text-md font-bold bg-btn1 text-white px-28 py-3 rounded ${
            disableClick && "hidden"
          }`}
          id="rollBtn"
          onClick={() => {
            const runBets = () => {

              for (let i = 0; i < 10; i++) {
                if (stopBet) {
                  console.log("enable click");
                  document
                    .getElementById("rollBtn")
                    .removeAttribute("disabled");
                  setDisableClick(false);
                  setStopBet(false);
                  break;
                }
                
              }
            };
            // To prevent spamming of bets
            setDisableClick(true);
            console.log("disable click");
            document
              .getElementById("rollBtn")
              .setAttribute("disabled", "true");
            runBets();
          }}>
          Roll Dice
        </button>
        <button
          type="button"
          className={`text-md font-bold bg-btn1 text-white px-28 py-3 rounded ${
            !disableClick && "hidden"
          }`}
          id="rollBtn"
          onClick={() => {
            setStopBet(() => {
              console.log("stop bet");
              return true;
            });
          }}>
          Stop Bet
        </button>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here's a problem if you use useState, there is a lag when states update and component re-renders. Meanwhile, the loop can go on, which you don't want.

I suggest you try this out with useRef, it will not re-render the whole component and do your job.

const bool = useRef(false);  // Replace the useState line with this.

onClick(() => bool.current = true); // Replace the stop logic with this.

if (bool.current) // Replace the if condition with this.
break;

I also suggest that for some questions, you clone what you want in the sandbox, so it is easier to actually see what you want or what's happening in the UI.

about 4 years ago · Juan Pablo Isaza Relatório

0

I think you should use useMemo instead of useState here, as you don't want to change the data while the component gets re-rendered

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