无法延迟执行funcRemove

时间:2018-11-20 23:36:33

标签: javascript event-handling alert

在将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');
}

1 个答案:

答案 0 :(得分:0)

if (tempImageView.getImage() == null)是一个异步函数,这意味着它是并行执行的。您需要将要在1000ms延迟后运行的代码放入setTimeout中的函数中。例如:

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中的任何内容都是回调函数https://developer.mozilla.org/en-US/docs/Glossary/Callback_function的一部分。

要根据情况正确使用回调和setTimeout,请执行以下操作:

setTimeout

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

matchCheck
相关问题