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);
}
}
disabled
in the setTimeout function.