最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - sleep is not defined in async function? - Stack Overflow

programmeradmin2浏览0评论

Im currently working on a memory game project. A function I am trying to implement, flips cards around after two seconds instead of having them flip instantly.

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

Im currently working on a memory game project. A function I am trying to implement, flips cards around after two seconds instead of having them flip instantly.

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 = [];
            }
        }
    }
}
Share Improve this question edited May 21, 2018 at 23:43 Yahya Essam 1,9122 gold badges25 silver badges44 bronze badges asked May 21, 2018 at 23:29 ak39464ak39464 1101 gold badge2 silver badges10 bronze badges 9
  • 3 I don't see anywhere in the code where sleep is defined..? – CertainPerformance Commented May 21, 2018 at 23:30
  • @CertainPerformance "await sleep(2000);" – ak39464 Commented May 21, 2018 at 23:31
  • 2 There, you're calling sleep, not defining it – CertainPerformance Commented May 21, 2018 at 23:31
  • you havent defined sleep what are you trying to do – Joe Warner Commented May 21, 2018 at 23:31
  • 1 want me to show you how to do it with timeout? – Joe Warner Commented May 21, 2018 at 23:37
 |  Show 4 more comments

3 Answers 3

Reset to default 11

Promises are easier to deal with than setTimeout. If you want to use something like the sleep you're describing, then define a function that returns a Promise that resolves after the inputted ms:

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

It'll keep code flatter than using setTimeout and callbacks.

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

instead of await sleep(2000); sleep is not a native stop the program but you can yield the same results with setTimeout

use

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

or without an arrow function

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

Using Node.js, this worked for me:

create a new function that resolves after sleep time:

async sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
          }

To use it, just call the function inside an async function:

async foobar() {
    await sleep(1000)
}
发布评论

评论列表(0)

  1. 暂无评论