Предотвращение появления сладкого предупреждения 2 после обнаружения последней пары карт

#javascript #sweetalert2

Вопрос:

В настоящее время я сталкиваюсь с этой проблемой, когда 2 sweetalert появляются один за другим после того, как найдена последняя пара карт. Я только недавно добавил setTimeout в sweetalert, потому что мой профессор хочет, чтобы предупреждение о сладком не появлялось сразу после нахождения пары карт, но теперь, как я упоминал ранее, когда я нашел последние пары карт, 2 sweetalert появляются одна за другой. кстати, я использовал sweetalert 2. Вот мой код:

 const cards = document.querySelectorAll('.memory-card')  let hasFlippedCard = false let lockBoard = false let firstCard, secondCard let matchCounter = 0 let timerCtrl = null // store the return value of setInterval  function flipCard() {  if (lockBoard) return  if (this === firstCard) return   this.classList.add('flip')   if (!hasFlippedCard) {  hasFlippedCard = true  firstCard = this   return  }   secondCard = this  checkForMatch() }  function checkForMatch() {  let isMatch = firstCard.dataset.framework === secondCard.dataset.framework  if (isMatch) {  matchCounter  = 1  disableCards()  setTimeout(function(){  Swal.fire({  imageUrl: 'https://unsplash.it/400/200',  imageWidth: 400,  imageHeight: 200,  imageAlt: 'Custom image',  html: 'lt;a href="//sweetalert2.github.io"gt;linkslt;/agt; ',  // confirmButtonText: 'Resume Game',  allowOutsideClick: false,  }).then(() =gt; {  time()  })  }, 1000);    clearInterval(timerCtrl)  if (matchCounter == cards.length / 2) {  Swal.fire({  title: 'Congratualtions!!!',  text: 'You finish the game '    counterVal    ' Moves. Thank you for playing',  allowOutsideClick: false,  })  setTimeout(timerCtrl) // it will stop the timer  }  } else {  unflipCards()  } }  function disableCards() {  firstCard.removeEventListener('click', flipCard)  secondCard.removeEventListener('click', flipCard)   resetBoard() }  function unflipCards() {  lockBoard = true   setTimeout(() =gt; {  firstCard.classList.remove('flip')  secondCard.classList.remove('flip')   resetBoard()  }, 500) }  function resetBoard() {  hasFlippedCard = false  lockBoard = false  firstCard = null  secondCard = null }  ; (function shuffle() {  cards.forEach(card =gt; {  let randomPos = Math.floor(Math.random() * 12)  card.style.order = randomPos  }) })()  cards.forEach(card =gt; card.addEventListener('click', flipCard))  function restartButton() {  location.reload() } var i = 0  function timer(id) {  if (id == '1') {  i    if (i === 1) {  time()  }  } else if (id == '2') {  //dri nimo e butang ang pause nga function  } else if (id == '3') {  //function for continue time  } }  var numr = 0  function countClick() {  numr    console.log(numr) }   var minutesLabel = document.getElementById('minutes') var secondsLabel = document.getElementById('seconds') var totalSeconds = 0  /*Timer*/ function time() {  function setTime() {    totalSeconds  secondsLabel.innerHTML = pad(totalSeconds % 60)  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60))  }   function pad(val) {  var valString = val   ''  if (valString.length lt; 2) {  return '0'   valString  } else {  return valString  }  }  timerCtrl = setInterval(setTime, 1000) }  var counterVal = 0  function incrementClick() {  updateDisplay(  counterVal) }  function resetCounter() {  counterVal = 0  updateDisplay(counterVal) }  function updateDisplay(val) {  document.getElementById('counter-label').innerHTML = val } 
 * {  margin: 0;  box-sizing: border-box; }  body {  background: url('https://github.com/FoxyStoat/memory-game/blob/master/assets/img/ignasi_pattern_s.png?raw=true'); }  h1 {  font-weight: 400;  text-shadow: 1px 1px 2px rgba(80, 80, 80, 0.6); }  .container {  display: flex;  justify-content: center;  align-items: center;  flex-direction: column; }  .memory-game {  width: 340px;  height: 340px;  display: flex;  flex-wrap: wrap;  perspective: 100%;  margin: 5px; }  .memory-card {  width: calc(25% - 10px);  height: calc(33.333% - 10px);  margin: 5px;  /* position: relative; */  /* transform: scale(1); */  transform-style: preserve-3d;  transition: transform 0.5s;  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3); }  .memory-card:active {  transform: scale(0.97);  transition: transform 0.2s; }  .memory-card.flip {  transform: rotateY(180deg); }  .front-face, .back-face {  width: 100%;  height: 100%;  /* padding: 1px; */  position: absolute;  /* border-radius: 5px; */  /* background: #1C7CCC; */  backface-visibility: hidden; }  .front-face {  transform: rotateY(180deg); }  .score-panel {  text-align: left;  width: 270px;  margin-bottom: 10px;  color: #0d0d0e; }  .score-panel .stars {  margin: 0;  padding: 0;  display: inline-block;  margin: 0 5px 0 0;  color: rgb(24, 23, 23); }  .score-panel .stars li {  list-style: none;  display: inline-block; }  .score-panel .timer {  display: inline;  position: absolute;  left: 50%; }  .score-panel .restart {  float: right;  cursor: pointer; }  @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {  .memory-game {  width: 860px;  min-height: 880px;  } }  @media only screen and (min-device-width: 375px) and (max-device-width: 812px) {  .memory-game {  width: 860px;  min-height: 880px;  } }  @media only screen and (min-device-width: 320px) and (max-device-width: 568px) {  .memory-game {  width: 860px;  min-height: 880px;  } }  .swal-wide {  width: 850px !important; } 
 lt;!DOCTYPE htmlgt; lt;html lang="en"gt; lt;headgt;  lt;meta charset="UTF-8"gt;  lt;titlegt;Memory Gamelt;/titlegt; lt;link rel = "stylesheet" href ="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"gt; lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"gt; lt;link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css"gt; lt;link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda"gt; lt;link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda"gt; lt;link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Gloria Hallelujah|Permanent Marker" gt; lt;link href="lt;?php echo base_url();?gt;resources/dist/css/style.css" rel="stylesheet"gt; lt;/headgt; lt;bodygt; lt;div class = "container"gt;  lt;h1gt;Memory Gamelt;/h1gt;  lt;section class="score-panel"gt;  lt;!-- lt;ul class="stars"gt;  lt;ligt;lt;i class="fa fa-star"gt;lt;/igt;lt;/ligt;  lt;ligt;lt;i class="fa fa-star"gt;lt;/igt;lt;/ligt;  lt;ligt;lt;i class="fa fa-star"gt;lt;/igt;lt;/ligt;  lt;/ulgt; --gt;   lt;spangt;Moves lt;span id = "counter-label"gt;0lt;/spangt;lt;/spangt;   lt;div class="timer"gt;  lt;label id="minutes"gt;00lt;/labelgt;:lt;label id="seconds"gt;00lt;/labelgt;  lt;/divgt;   lt;div class="restart"gt;  lt;button onclick="restartButton()" class="fa fa-repeat"gt;lt;/buttongt;  lt;!-- lt;div class="col text-center"gt;  lt;button button type = "button" class = "btn btn-danger"gt;Resetlt;/buttongt;  lt;/divgt; --gt;  lt;/divgt;  lt;/sectiongt;   lt;div class="memory-game "gt;  lt;div class="memory-card" data-framework="aurelia"gt;  lt;img class="front-face" src="lt;?php echo base_url();?gt;/resources/dist/img/fb.png" class = "img-fluid"alt="fb" /gt;  lt;img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="lt;?php echo base_url();?gt;/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" /gt;  lt;/divgt;   lt;div class="memory-card" data-framework="aurelia"gt;  lt;img class="front-face" src="lt;?php echo base_url();?gt;/resources/dist/img/fb.png" class = "img-fluid"alt="fb" /gt;  lt;img onclick = "incrementClick(); timer('1');" id = "back" class="back-face" src="lt;?php echo base_url();?gt;/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" /gt;  lt;/divgt;   lt;div class="memory-card" data-framework="vue"gt;  lt;img class="front-face" src="lt;?php echo base_url();?gt;/resources/dist/img/js.jpg" class = "img-fluid"alt="js" /gt;  lt;img onclick = "incrementClick(); timer('1');" id = "back"id="back" class="back-face" src="lt;?php echo base_url();?gt;/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" /gt;  lt;/divgt;    lt;div class="memory-card" data-framework="vue"gt;  lt;img class="front-face" src="lt;?php echo base_url();?gt;/resources/dist/img/js.jpg" class = "img-fluid"alt="js" /gt;  lt;img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="lt;?php echo base_url();?gt;/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" /gt;  lt;/divgt;       lt;/divgt;   lt;/divgt;      

а также я хочу, чтобы изображение перевернутой карты было видно в sweetalert, когда будут найдены пары карт. Веб-разработчик-новичок здесь. Я ценю любую помощь, которую вы можете мне оказать. Заранее спасибо.

Комментарии:

1. Сначала вы проверяете if (matchCounter == cards.length / 2) , и если это правда, то показываете всплывающее окно «Конец игры». Если нет, то покажите другое всплывающее окно.

2. @aerial301 спасибо вам за вашу помощь. 2-я сладкая тревога теперь не появлялась. Могу ли я также спросить, смогу ли я показать изображение парных карт, найденных в предупреждении sweet? я не могу найти никаких зацепок к тому, как я это сделаю