sleep 没有在异步函数中定义?

sleep is not defined in async function?

我目前正在做一个记忆游戏项目。我正在尝试实现的一个功能是在两秒后翻转卡片,而不是让它们立即翻转。

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

at this point of the program is where I plan to flip the cards back over when the user has already looked at them.

So what I did was create an asyn function called flip. I placed an await sleep inside to pause program execution but all i did was recieve 'sleep is not defined' error.

I am not sure why this is happening since the sleep function IS defined inside the flip function.

                // 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 = [];
            }
        }
    }
}

https://developer.mozilla.org/ro/docs/Web/API/window.setTimeout

而不是await sleep(2000); 睡眠不是本机停止程序,但您可以使用 setTimeout

产生相同的结果

使用

window.setTimeout(() => {
  Array.from(openCards).forEach(function(card) {
    card.classList.remove('mismatch')
    card.classList.remove('open');
    card.classList.remove('show');
  });
}, 2000);

或者没有箭头函数

console.log('1');
window.setTimeout(() => {
  console.log('2');
}, 2000);
console.log('3');

Promise 比 setTimeout 更容易处理。如果你想使用你描述的 sleep 之类的东西,那么定义一个函数 returns 一个在输入 ms:

之后解析的 Promise

const sleep = ms => new Promise(res => setTimeout(res, ms));

(async () => {
  console.log('1');
  await sleep(500);
  console.log('2');
  await sleep(1500);
  console.log('3');
})();

它会使代码比使用 setTimeout 和回调更简洁。