Help with memory project

Im making a memory game. There is a bug that if you click quick enough you can turn over more than two cards before the cards turn back over. can someone help me with how to solve this?


You could check for the cards that are already flipped and return (exit the function) if there are 2 or more:

document.querySelectorAll('.card.flipped').length >= 2

This helps. But now when I put this in my code I can turn a maximum of 2 cards, and cant continue with the game.

LOL! Sorry, didn’t think of it :sweat_smile:.

Well, You’ll have to think of a way of telling which cards are the current cards being played.

You could, for example, save the current play to an array:

let currentPlay = [];

Then, when a card is clicked, check for this conditions:

  • When the currentPlay has two elements, return; no more cards can be clicked.
  • When the currentPlay has been already clicked (has class flipped), return (You’re already doing this).
  • Push the card into the array (currenPlay.push(card)). Since we’re already checking if the array has two elements, at this point we will never have more than two.
  • And finally, check again if there are two cards; if there are, then validate that they are equal and reset the array (currentPlay = []). This sounds weird since we’re already checking for the 2 elements, but this check is different, since You just added an element.

Look at this code:

function cardClicked(elCard) {
  if (currentPlay.length === 2) {

  // If the user clicked an already flipped card - do nothing and return from the function
  if (elCard.classList.contains("flipped")) {

  // Flip it

  if (currentPlay.length === 2) {
    console.debug("El:", currentPlay[0]);
    const card1 = currentPlay[0].dataset.card;
    const card2 = currentPlay[1].dataset.card;

    if (card1 != card2) {
      setTimeout(function() {
        // Do not reset the array outside the timeout, otherwise it will be undefined here.
        currentPlay = [];
      }, 1000);
    } else {

      currentPlay = [];

      // All cards flipped!
      if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {;

And here You can see it working (I cloned Your code).