3noki
3noki

Reputation: 397

Need to wait for setInterval process to complete

Full code here; https://codepen.io/3noki/pen/xjyErQ?editors=0011

I want this, when two cards are open, to pause, then flip them back over if not a match. But currently I can keep clicking while this interval is running/ before the cards have turned back over, causing problems.

Is there a way to make everything, or a new click, to wait until the interval is complete?

$(".card").on("click", function cardFlip() {
  if (!this.classList.contains('open') && openedCardsList.length <= 2) {
    this.classList.toggle('open');
    openedCardsList.push(this);
    if ( openedCardsList.length == 2) {
    checkForMatch();
    }else {}
  }
  else {}
});

function checkForMatch() {
    let a = $('i.fa', openedCardsList[0]).data('fa');
    let b = $('i.fa', openedCardsList[1]).data('fa');
    let eq = ( a && b && a === b );
    if (eq) {     
      $(openedCardsList[0]).removeClass('open').addClass('match');
      $(openedCardsList[1]).toggleClass('open match');
      openedCardsList = [];
      matched++;
    }
  else {unFlip();}
}

setInterval( function unFlip() {
  openedCardsList[0].classList.toggle('open');
  openedCardsList[1].classList.toggle('open');
  openedCardsList = [];
}, 3000);

Upvotes: 0

Views: 82

Answers (1)

jdickel
jdickel

Reputation: 1457

You should remove the setInterval since this is always triggering after three seconds. You only want to call the unflip() method after comparing. So you would need to use a setTimeout(). Now the unflip() method is only called after selecting 2 cards. Note that the unflip() function is nested in a function() { }. Otherwise the timeout won't take any effect.

I also changed your if clause from openedCardsList.length <= 2 to openedCardsList.length < 2 since you only want to have a maximum of 2 open cards.

Here is your codepen

Upvotes: 1

Related Questions