简体   繁体   中英

In Javascript How do I prevent other functions from being invoked while under the setTimeout duration?

I am doing a tic-tac-toe game.

I included a setTimeout function so that before the computer makes its move, it will look like it is "thinking" before the computer actually leaves a mark in the board.

However, I noticed that while the computer is "thinking" I can make my move thereby defeating the purpose of having an opponent make their move first before I can make another of my own (if that makes sense)

Example:

(My turn) I mark a box with circle
(Computer turn) Computer 'thinks'...

  • I make a move while computer is thinking
  • My move leaves a mark in the board before computer makes its move, meaning a function still gets invoked while under the setTimeout duration.

How do I prevent this? Is this possible?

setTimeout(compTurn, 1000)

In your click listener for when the player takes a turn, check to see if the player is permitted to play first. Toggle a boolean when compTurn gets scheduled, and toggle it off when compTurn finishes:

// Start of game:
let playerTurn = true;

// ...

// Make computer take a turn:

playerTurn = false;
setTimeout(compTurn, 1000);
const compTurn = () => {
  // ...
  playerTurn = true;
};
board.addEventListener('click', (e) => {
  if (!playerTurn) return;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM