我目前正在开发一款记忆游戏。我想实现的一个功能是,在两秒钟后翻转卡片,而不是立即翻转。
let openCards = [];
function cardActions(card) {
// prevent function from adding two classes over and over again
if (!(card.classList.contains('open'))) {
// display the card's symbol
card.className += ' open';
card.className += ' show';
// add card to list of open cards
openCards.push(card);
if(openCards.length === 2) {
if(openCards[0].innerHTML === openCards[1].innerHTML) {
// add the match class
Array.from(openCards).forEach(function(card){
card.className += ' match';
});
console.log('match');
// empty open cards
openCards = [];
} else {
Array.from(openCards).forEach(function(card) {
// add the mismatch class
card.className += ' mismatch';
});
在程序的这一点上,当用户已经查看了卡片时,我计划翻转卡片。因此,我创建了一个名为flip的异步函数。我在其中放置了一个等待sleep的await函数,以暂停程序执行,但我收到了“未定义的sleep”错误。
我不确定为什么会发生这种情况,因为sleep函数确实在flip函数内定义了。
// flip cards around
async function flip() {
await sleep(2000);
Array.from(openCards).forEach(function(card) {
card.classList.remove('mismatch')
card.classList.remove('open');
card.classList.remove('show');
});
}
// give user time to look at the cards
flip();
console.log('these dont match');
// empty open cards
openCards = [];
}
}
}
}
sleep
函数,这是为什么? - CertainPerformance