首页 > 解决方案 > 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.

标签: javascript

解决方案


您可以这样做(使用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)
    }

推荐阅读