[英]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.我包含了一个 setTimeout 函数,以便在计算机移动之前,它看起来像是在“思考”,然后计算机实际在板上留下标记。
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'... (计算机转向)计算机“思考”...
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:当
compTurn
被安排时切换一个布尔值,并在compTurn
完成时compTurn
其关闭:
// 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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.