Search code examples
javascriptasync-awaitsleep

sleep is not defined in async function?


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

Solution

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