I'm making a memory game. It already sort of works, but when I choose two cards that aren't the same picture, they flip back instantly, without showing the user what is on the second card. I think I should use setTimeout(), but for now it only made my flipBack() function not work at all. Maybe, I am using it incorrectly or in the wrong place.
I tried putting both the flipBack() and setTimeout(flipBack, 5000) inside "else if", outside of it, outside of my revealCard() function.
I'm only getting "Uncaught TypeError: Cannot read properties of undefined (reading 'style') at flipBack (memory game.js:61:35)" in the console. It seems that setTimeout cannot execute flipBack() or something like that.
let board = document.getElementById("board");
let score = document.getElementById("score");
let fails = document.getElementById("fails");
let cards = document.querySelectorAll(".card");
// add eventListener to every card
for (let i = 0; i < 6; i++) {
cards[i].addEventListener("click", revealCard);
}
let revealCounter = 2;
let imgAltArray = [];
let latestTwoRevealedCards = [];
let points = 0;
let wrongGuesses = 0;
function revealCard(event) {
if (revealCounter > 0) {
let cardImg = event.target.firstChild;
// make card "flip", so you can see the picture
cardImg.style.visibility = "visible";
imgAltArray.push(cardImg.alt);
latestTwoRevealedCards.push(cardImg);
console.log(imgAltArray);
revealCounter--;
// check if both cards have the same picture on them by comparing alt parameters
if (revealCounter == 0 && imgAltArray[0] === imgAltArray[1]) {
imgAltArray = [];
latestTwoRevealedCards = [];
points++
score.textContent = `Score: ${points}`;
revealCounter = 2;
}
else if (revealCounter == 0 && imgAltArray[0] !== imgAltArray[1]) {
wrongGuesses++;
fails.textContent = `Failed attempts: ${wrongGuesses}`
imgAltArray = [];
// make cards flip back
setTimeout(flipBack, 5000);
latestTwoRevealedCards = [];
revealCounter = 2;
}
}
}
// TIMEOUT DOESN"T WORK
function flipBack() {
for (let i = 1; i >= 0; i--) {
latestTwoRevealedCards[i].style.visibility = "hidden";
}
}
latestTwoRevealedCards[i] This element may be undefined