Mark
Mark

Reputation: 169

Javascript version of a sleep function

I'm making a guessing game. When the user guesses between two foods, I want to show the calories of both foods before rendering the next component. What's Javascript's version of sleep 2?

clickHandler = e => {
    this.setState({
      showCalories: true
    });

    // PAUSE HERE FOR 2 SECONDS

    if (e.target.src === this.state.mostCalories.attributes.image) {
      this.setState({
        currentGame: {
          id: this.state.currentGame.id,
          score: this.state.currentGame.score + 1,
          initials: ""
        }
      });
      this.newFoods();
    } else {
      this.gameOver();
    }
  };

I've read a few answers on here but they're either outdated or I get a parsing error. I've tried await new Promise(r => setTimeout(r, 2000)); and prefixed the function with async as stated here.

Upvotes: 0

Views: 114

Answers (4)

Addis
Addis

Reputation: 2530

You can do it inside an asynchronous function. But unlike in case of JAVA's sleep, you can't use it in synchronous operation.

async function sleep(seconds) {
    console.log('start');
    await new Promise( resolve => {
        console.log('now on sleep...');
        setTimeout(resolve, seconds);
    });
    console.log('end');
}

sleep(3000);

Upvotes: 0

epascarello
epascarello

Reputation: 207511

You can just use a timeout

clickHandler = e => {
  this.setState({
    showCalories: true
  });

  window.setTimeout(() => {
    if (e.target.src === this.state.mostCalories.attributes.image) {
      this.setState({
        currentGame: {
          id: this.state.currentGame.id,
          score: this.state.currentGame.score + 1,
          initials: ""
        }
      });
      this.newFoods();
    } else {
      this.gameOver();
    }
  }, 2000);
};

Upvotes: 1

TBouder
TBouder

Reputation: 2719

You can do this (with setTimeout)

setTimeout(() => {
    //THE THINGS TO RUN AFTER X MS
}, TIME TO SLEEP IN MS)
    clickHandler = e => {
        this.setState({showCalories: true});

        // PAUSE HERE FOR 2 SECONDS
        setTimeout(() => {
            if (e.target.src === this.state.mostCalories.attributes.image) {
                this.setState({
                    currentGame: {
                        id: this.state.currentGame.id,
                        score: this.state.currentGame.score + 1,
                        initials: ""
                    }
                });
                this.newFoods();
            } else {
              this.gameOver();
            }
        }, 2000)
    }

Upvotes: 3

Hurried-Helpful
Hurried-Helpful

Reputation: 2000

Make the event handler an async function. And simply await a timeout Promise.

clickHandler = async e => {
    this.setState({
      showCalories: true
    });

    // PAUSE HERE FOR 2 SECONDS
    await new Promise(r => setTimeout(r, 2000))

    if (e.target.src === this.state.mostCalories.attributes.image) {
      this.setState({
        currentGame: {
          id: this.state.currentGame.id,
          score: this.state.currentGame.score + 1,
          initials: ""
        }
      });
      this.newFoods();
    } else {
      this.gameOver();
    }
  };

Upvotes: 1

Related Questions