1

I'm having a problem. I can't get out of addEventListener when specific value is get after enormous time of clicking specific images.

function game(role){    
    
    playRound(role, computerPlay());
    console.log(`Player: ${player_count} Computer: ${computer_count}`);
        
}



const buttons = document.querySelectorAll('button');

function pickRole(buttons){
    buttons.forEach((button) => {
        button.addEventListener('click', () => {
            if (button.className === "btn-1"){
                role = "rock";
            }else if (button.className === "btn-2"){
                role = "paper";
            }else if (button.className === "btn-3"){
                role = "scissors";
            }
            
            game(role);
            
        });
        
    });

}

pickRole(buttons);

My program is checking each statement inside playRound() function, and after 5 wins are get, I want it to be able to get out.

Ceki
  • 31
  • 1
  • 6
  • Does this answer your question? [Wait for click in loop](https://stackoverflow.com/questions/23754587/wait-for-click-in-loop) – Ivar Apr 14 '21 at 08:07
  • That forEach loop runs exactly once, when the page loads. This is fine, since it adds an event listener to each button, exactly as you're supposed to do here. If you want the button clicks to do something different after 5 wins, a) count the wins b) add `if (wins === 5)` inside the inner function and don't call `game(role)` but do something else instead. –  Apr 14 '21 at 08:11
  • I tried it, but somehow it still didn't work.. could u give me some example? btw I have 2 global variables player_count and computer_count that are counted inside that playRound() function, but those values are never shown outside bcs, when I start clicking images, I think I'm getting infinite program. – Ceki Apr 14 '21 at 08:17
  • I solved it thanks, I tried every other solutions except this simple one if else :D – Ceki Apr 14 '21 at 08:22
  • The `forEach` has no connection/relation to the events and the event-handling. You don't want to stop the loop. You want to somehow not proceed with some processes inside your event-handler function. Thus, think about a condition which can be validated inside your handler. Depending on this very condition's return value one has to decide whether to proceed with e.g. invoking the `game` function or not. – Peter Seliger Apr 14 '21 at 08:26

0 Answers0