如何停止其他代码运行,直到setTimeout()完成运行? [英] How to stop other code from running until setTimeout() finishes running?

查看:71
本文介绍了如何停止其他代码运行,直到setTimeout()完成运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的存储卡游戏.如果您连续单击两张相同的卡片,它们将保持打开状态.如果您连续单击两张不同的卡片,它们都将在1.5秒内关闭.为此,我使用setTimeout();.但是,如果在1.5秒内用户单击任何其他卡,则事件侦听器功能将再次开始运行,而setTimeout尚未首次完成运行.这会使游戏崩溃.如何防止其他代码在setTimeout第一次完成运行之前运行?任何建议都将不胜感激!

I am making a simple memory card game. If you click on two cards in a row that are the same they stay open. If you click on two cards in a row that are not the same they both close in 1.5s. For that I use setTimeout(); However, if during that 1.5s user clicks on any other card, event listener function starts running again while setTimeout have not finished running for the first time. This crashes the game. How to prevent other code from running until setTimeout finishes running for the first time? Any suggestion is greatly appreciated!

const cards = document.querySelectorAll('.container__small');
let hasFlippedCard = false;
let firstCard, secondCard;
let lockBoard = false;

cards.forEach(function (card) {
  return card.addEventListener('click', flipCard);
});

function flipCard(){
  this.classList.add('flip');
  if(!hasFlippedCard){ 
    //first click
    hasFlippedCard = true;
    firstCard = this;
  }else {
    //second click
    hasFlippedCard = false;
    secondCard = this;
    setTimeout(function(){
      if(firstCard.dataset.framework !== secondCard.dataset.framework ){
        firstCard.classList.remove('flip');
        secondCard.classList.remove('flip');
      }
    }, 1500);
  }
}

推荐答案

function flipCard(){
  if (lockBoard) {
    return
  }
....

结束您的setTimeout函数

end in your setTimeout function

lockBoard = true
setTimeout(function(){
  ....
  lockBoard = false
}, 1500)

这篇关于如何停止其他代码运行,直到setTimeout()完成运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆