Skip to content
Advertisement

How can I wait for a click to be executed?

I am trying to figure out how I can update the playerValue for my Rock Scissor Paper game. I have a function that registers a button click and should then update the playerValue accordingly(1,2 or three depending on which button was clicked). The problem is, when I call the function, the playerValue remains 0 and I don’t know what I need to change to fix that. playerValue itself is defined at the very beginning of my file. It starts out as 0.

Here is my JavaScript code(or at least the relevant part of it):

//register button click and:
function player_choose_value(){
    //check which button has been clicked -> rock 1, scissor 2 or paper 3
    btnRock.addEventListener("click", () =>{
        playerValue = 1;
    });

    btnScissor.addEventListener("click", () =>{
        playerValue = 2;
    });
    
    btnPaper.addEventListener("click", () =>{
        playerValue = 3;
    });
}

This here is where the playerValue is meant to be used. The playerValue is always 0. I think that is because the player_choose_value() function does not wait for the click event to happen. So the function is executed but the user does not have the chance to actually click a button, so it stays 0:

function play_round(){
    let computerValue = computer_choose_value();
    player_choose_value();//is always zero
    console.log(playerValue);
    won_tie_lost(computerValue, playerValue);
}

I was wondering how I could add a “wait for one of the three buttons to be clicked” functionality?

Advertisement

Answer

In your case, player_choose_value doesn’t wait until the player has actually picked a value.

You could probably do this using async await/promises:

function player_choose_value(){
  return new Promise(resolve => {
    bntRock.onclick = () => resolve(1)
    btnScissor.onclick = () => resolve(2)
    btnPaper.onclick = () => resolve(3)
  })
}

async function play_round(){
  let computerValue = computer_choose_value();
  const playerValue = await player_choose_value();
  console.log(playerValue);
  won_tie_lost(computerValue, playerValue);
}

;(async function main() {
  while (true) { // Keep repeating the game
    await play_round()
  }
})()
Advertisement