3
\$\begingroup\$

I've developed a small memory game, the game contains a function to flip cards for every turn. I'm looping thru the array containing the images every time to pick one card. I'm sure there's away to optimize this function so I don't have to loop through the array every time in order to just turn one card. But I'm a bit clueless how to proceed and would like to get some guidance of how I possibly could optimize this function with vanilla javascript and without objects.

function flipCards() {
  var i; // Loopvariabel

  // For loop
  for (i = 0; i < cardsElems.length; i++) {
    if (this == cardsElems[i]) {
      if (cardsCounter > 1) {
        return;
      }

      cardsElems[i].className = "brickFront";
      cardsElems[i].src = "pics/" + allCards[i] + ".png";
      removeListener(cardsElems[i], "click", flipCards);
      if (cardsCounter < 1) {
        card1 = i;
      } else {
        card2 = i;
      }
      cardsCounter += 1;
    }
  }

  if (cardsCounter < 2) {
    nextBtn.disabled = true; // Avaktivera knapp
  }

  if (cardsCounter == 2) {
    turns += 1;
    turnNr.innerHTML = turns;
    nextBtn.disabled = false; // Aktivera knapp
  }

  if (brickBack.length == 0) {
    endGame();
  }
} // End flipCards

\$\endgroup\$
1
  • \$\begingroup\$ Before you start optimizing, is it actually too slow? Do you have any profiling data to share? \$\endgroup\$ – Emily L. Jul 24 '19 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.