maxineheadroom
maxineheadroom

Reputation: 91

setTimeout only functioning on initial clicks, not those following (jquery)

Working on a memory game. Trying to use setTimeout so that the cards revert to their original state when there is not a match. The function works on the initial clicks, the cards revert no problem when they do not match each other. However once there IS a match and I continue to play through the cards no longer work with the time out, and will only revert to their original state upon the click of a third card (which is now it functions without the added setTimeout). This is very abbreviated obviously but I think I have included the related bits, if not of course let me know.

cardFlip = 0;

$box.on("click", function() {
cardFlip++;
});

else if (cardFlip == 2){
    $box.css("pointerEvents", "none");
    setTimeout( () => {
    $(".active").removeClass("active");
    $(".first").removeClass("first");
    $(".second").removeClass("second");
    $box.css("pointerEvents", "all");   
    }, 800);
    cardFlip = 0;

  }

I thought by having the cardFlip = 0; at the end of the function that would start the count to 0 again but I'm obviously mistaken.

Upvotes: 0

Views: 36

Answers (1)

Mox
Mox

Reputation: 598

Create a flag variable which will be checked for before anything is done within the time out. If the flag variable is set, the timeout should stop execution at that point. You should set this variable once you have a match.

setTimeout( () => {
if (!match) {
$(".active").removeClass("active");
$(".first").removeClass("first");
$(".second").removeClass("second");
$box.css("pointerEvents", "all");   
}}, 800);

The main reason for which I suspect you're having an issue from what I can see, is because the Timeout is set to 800ms, you could be potentially clicking cards within that timeframe.

Upvotes: 1

Related Questions