javascript - 无法延迟执行 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');
}
解决方案
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++;
}
推荐阅读
- javascript - 如何在函数内取消超时
- java - 问:Saxon XQuery 自定义解析器
- linux - 蓝牙突然关闭并且不再活动
- c - 读取文件到链表 C
- javascript - javascript for循环没有为类中的每个按钮打印正确的数据集
- r - 展开数据表,添加新行并按组替换 NA 值
- f# - F#- 如何在 F# 中使用 Assert.Multiple
- python - 当标准偏差大于python中的平均值时,如何绘制带有误差线的条形图?
- sql - 当只有一行满足 WHERE 子句的要求时,是否有返回一组行的 SQL 查询/函数?
- postgresql - 如何使用 UUID 作为 Postgresql 中的外键与休眠