I’m trying to code a card game i made using html, css, and js for practice, and i am trying to get clicked card divs to display in the center of the board, and it works for clicking once, but if the user clicks multiple times within the set timeout, it resets the original div image to the one selected before. I tried using a boolean if statement to return out of the function if within the 3 seconds, but it can’t access the variable if i initialize outside of the function.
let clickCard = true;
function clickedCard(clicked) {
if (!clickCard) {
return;
}
let ogStyle = window.getComputedStyle(document.getElementById("playerPlayed"));
let ogImg = ogStyle.getPropertyValue("background-image");
let clickedStyle = window.getComputedStyle(clicked);
let backImg = clickedStyle.getPropertyValue("background-image");
let playedDiv = document.getElementById("playerPlayed");
playedDiv.style.backgroundImage = backImg;
playedDiv.style.backgroundColor = "azure";
let cpuCard = cpuPlayCard();
let cpuArr = document.getElementsByClassName("cpuCard");
let cpuArrIndex = cpuCard - 1;
let cpuOgStyle = window.getComputedStyle(document.getElementById("cpuPlayed"));
let cpuOgImg = cpuOgStyle.getPropertyValue("background-image");
let cpuStyle = window.getComputedStyle(cpuArr[cpuArrIndex]);
let cpuBackImg = cpuStyle.getPropertyValue("background-image");
let cpuDiv = document.getElementById("cpuPlayed");
cpuDiv.style.backgroundImage = cpuBackImg;
cpuDiv.style.backgroundColor = "azure";
clickCard = false;
setTimeout(function () {
playedDiv.style.backgroundImage = ogImg;
playedDiv.style.backgroundColor = "none";
clickCard = true;
}, 3000);
setTimeout(function () {
cpuDiv.style.backgroundImage = cpuOgImg;
cpuDiv.style.backgroundColor = "none";
clickCard = true;
}, 3000);
let playerCard = clicked.dataset.card;
}
function cpuPlayCard() {
let cards = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5];
let rand = Math.floor(Math.random() * cards.length);
let cpuCard = cards[rand];
return cpuCard;
}
I’ve tried setting it as var and putting the variable inside the statement but that just sets it to true whenever the divs are clicked anyway. The error says, “cannot access clickCard before initialization.” Also I use onclick within the div tag in html. I am both confused and new to this and it is my first personal project.

