Search code examples
javascriptreactjsloopsonclickonclicklistener

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>

Solution

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