ak39464
ak39464

Reputation: 110

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

Upvotes: 4

Views: 25618

Answers (3)

Daniel Freitas
Daniel Freitas

Reputation: 1

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

Upvotes: 0

Joe Warner
Joe Warner

Reputation: 3452

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

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 370779

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.

Upvotes: 11

Related Questions