简体   繁体   English

在 Javascript 中如何防止在 setTimeout 持续时间内调用其他函数?

[英]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'... (计算机转向)计算机“思考”...

  • 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.我的移动在计算机移动之前在板上留下了一个标记,这意味着在 setTimeout 持续时间内仍然会调用一个函数。

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.

相关问题 如何防止此 javascript 被评估? - How do I prevent this javascript from being evaluated? 如何使用Javascript防止在输入上输入除数字以外的其他字符 - How can I prevent other characters from being inputted on an input except numbers using Javascript 如何在Javascript中使用带有“do while”循环的setTimeout? - How to use setTimeout with a "do while" loop in Javascript? 除了我在javascript中指定的方式外,如何防止野生动物园使用命令键? - How do I prevent safari from using the command key other than how I specified it in my javascript? 如何防止对JavaScript:URL进行空格编码? - How do I prevent spaces from being URL encoded for a `javascript:` URL? 如何防止按键被反复触发 - JavaScript / jQuery - How do I prevent key press from repeatedly being fired - JavaScript/jQuery 如何防止javascript编写的内容存储在Firefox的wyciwyg缓存中? - How do I prevent javascript written content from being stored in Firefox's wyciwyg cache? 如何在 div 中显示 javascript 列表中的所有项目? - How do I display all the items from a javascript list under each other in a div? 如何防止闭包保留javascript函数的参数? - How do I prevent an argument to a javascript function being retained by a closure? JavaScript函数阻止执行C#函数? - JavaScript functions prevent C# functions from being executed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM