need to click twice on a button
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
Answer
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM