need to click twice on a button

- 1 answer

Ad

I have programmed a simple game where I used a bootstrap button to start a new game or do another game.

The first click (to start a new game) works well. Then when I want to do another game (by stopping and reinitializing the current game), it works also.

My problem is located in the reinitialization of this latter game (so, the second restart): I have to click the bootstrap button twice.

Here is the Javascript code snippet (the bootstrap button is buttonNewGame):

var buttonNewGame = document.getElementById('buttonNewGame');

function startGame() {
  // If currentGame then call initGame
  if (isCurrentGame) {
    isCurrentGame = false;
    initGame();
    console.log('HERE : stop and reinitialize current game');
  } 
  else {
    isCurrentGame = true;
  }

  // Call main function
  currentGame();
}

For the situation where I need to click twice, the console.log('HERE : stop and reinitialize current game'); shows nothing for the first click, then it calls startGame() at the second click.

Is this related to a problem of focus or a problem with the bootstrap button?

Thanks

Ad

Answer

Ad

If you follow the order of execution, you will notice that the first time you go into the startGame() the value for the isCurrentGame is false which is why it does not print the console.log.

The first time it goes in the startGame(), the value of isCurrentGame is changed to true, which is why, when you go in the second time. It goes inside the if condition.

To solve this, you would need to reset the value of isCurrentGame to true when the button is invoked

First time:

The value of isCurrentGame is false, so it will go in the else and will be assigned true.

if (isCurrentGame) {
    isCurrentGame = false;
    initGame();
    console.log('HERE : stop and reinitialize current game');
} else
    isCurrentGame = true;

the second time it goes in, the isCurrentGame is true, so it'll go inside the if condition and invoke the initGame() and will print console.log

Ad
source: stackoverflow.com
Ad