首页 > 解决方案 > 无法延迟执行 funcRemove

问题描述

我有一个问题是延迟执行funcRemove直到alert火灾发生后。

我尝试使用setTimeout,但我不断收到错误消息,指出该remove属性不存在。我如何完成延迟执行funcRemove直到alert火灾发生后?

const listAddCard = document.querySelectorAll('.card'); const moveElem = document.querySelector('.moves');

let turnCheck = 0;
let cardChecker = '';
let prevCard = '';
let moves = 3;

let matchCheck = function(evtObj){
  funcShow(evtObj);  
  console.log(turnCheck);
     if(turnCheck===1){
        setTimeout(function(){}, 1000);
        if(evtObj.target.innerHTML===cardChecker){
            evtObj.target.classList.add('match');
            prevCard.classList.add('match');
        }
        else{

            alert('No match');
        }
        funcRemove(prevCard, evtObj);
        turnCheck = 0;
        cardChecker = '';
        prevCard = '';
        moves++;
        moveElem.innerHTML = moves;
        return;
     }
     prevCard = evtObj.target;
     cardChecker = evtObj.target.innerHTML;
     turnCheck++;
 }

 let funcShow = function(e){
    e.target.classList.add('open', 'show');
    console.log('funcShow');
 }

const cardDeck = document.querySelectorAll('.card');
 for(var i=0;i<cardDeck.length;i++){
     cardDeck[i].addEventListener('click', matchCheck);
    }

let funcRemove = function (p1,p2){

        setTimeout(function(){}, 1000);    
        p1.classList.remove('open', 'show');
        p2.target.classList.remove('open', 'show');
}

标签: javascriptevent-handlingalert

解决方案


setTimeout是一个异步函数,这意味着它是并行执行的。您需要将要在 1000 毫秒延迟后运行的代码放入函数中setTimeout。例如:

console.log("Print #1");
setTimeout(function() {
    console.log("Print me after 1000ms");
}, 1000);
console.log("Print #2");

"Print 2"将在之后打印,"Print 1""Print me after 1000ms"稍后将打印。

此外,您不能简单地返回setTimeout. 您放入的任何内容setTimeout都是回调函数的一部分:https ://developer.mozilla.org/en-US/docs/Glossary/Callback_function 。

setTimeout要在您的情况下正确使用回调,请执行以下操作:

let funcRemove = function (p1,p2, callback){
    p1.classList.remove('open', 'show');
    p2.target.classList.remove('open', 'show');
    setTimeout(callback, 1000);    
}

matchCheck

let matchCheck = function(evtObj){
funcShow(evtObj);  
console.log(turnCheck);
   if(turnCheck===1){
      setTimeout(function(){}, 1000);
      if(evtObj.target.innerHTML===cardChecker){
          evtObj.target.classList.add('match');
          prevCard.classList.add('match');
      }
      else{
          alert('No match');
      }
      funcRemove(prevCard, evtObj, function() {
          // this part is executed 1000ms later
          turnCheck = 0;
          cardChecker = '';
          prevCard = '';
          moves++;
          moveElem.innerHTML = moves;
      })

      return;
   }
   prevCard = evtObj.target;
   cardChecker = evtObj.target.innerHTML;
   turnCheck++;
}

推荐阅读