0

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.

Mark
  • 169
  • 1
  • 1
  • 10

4 Answers4

3

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)
    }
TBouder
  • 2,539
  • 1
  • 14
  • 29
  • This almost seems to work. I get an error on the argument for the if statement saying "TypeError: Cannot read property 'src' of null". Why is that? – Mark Jan 21 '20 at 22:42
  • Seems to be an error with `e.target.src`. Make sure `e.target` is not `undefined` ! – TBouder Jan 21 '20 at 22:53
1

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();
    }
  };
Hurried-Helpful
  • 1,850
  • 5
  • 15
1

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);
};
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

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);
Addis
  • 2,480
  • 2
  • 13
  • 21