jer*_*ern 0 javascript sleep async-await
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';
});
Run Code Online (Sandbox Code Playgroud)
在程序的这一点上,我计划在用户已经看过卡片时将卡片翻转回来。
所以我所做的是创建一个名为flip 的异步函数。我在里面放置了一个 await sleep 来暂停程序执行,但我所做的只是收到“未定义睡眠”错误。
我不确定为什么会发生这种情况,因为 sleep 函数是在翻转函数中定义的。
// 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 = [];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Promise 比setTimeout
. 如果你想使用sleep
你所描述的类似的东西,那么定义一个函数,它返回一个在输入 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');
})();
Run Code Online (Sandbox Code Playgroud)
它会使代码比使用setTimeout
和回调更平坦。
归档时间: |
|
查看次数: |
9392 次 |
最近记录: |