I am creating a little game:
I would like to pause my program to wait for mouse input before continuing to another player’s turn, then wait for another input and remove the first event listener.
This is what I have so far
function handactive(event) {
// do something
}
game_ended = false
turn = 1
while (game_ended == false) {
if (turn % 2 != 0) {
player2hand.removeEventListener('click', handactive)
player1hand.addEventListener('click', handactive)
// wait until the above is triggered
}
else {
player1hand.removeEventListener('click', handactive)
player2hand.addEventListener('click', handactive)
// wait until the above is triggered
}
if (turn > 3) {
game_ended = true // will add logic for the game end later
}
turn++
}
I’m just not sure how to go about waiting for the event to be triggered before proceeding with the loop, right now it just removes the event listener before the player can click.
Thank you!
2
Answers
You just need a judgment in the EventListener but not a while loop
Using a while loop to wait for user input synchronously is generally NOT a good idea in JavaScript, especially in the context of a web application where user input is event-driven. JavaScript operates on a single-threaded event loop, and synchronous code execution like a while loop can block the thread, making your application unresponsive.
Instead, you should leverage the event-driven nature of JavaScript. Here’s a simple example using callbacks and promises:
In this example:
This way, your code becomes more asynchronous and event-driven, allowing for a smoother user experience. Remember to adapt the game logic and event handling according to your specific requirements.