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

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

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 Denunciar

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 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