我正在做一个猜谜游戏。当用户在两种食物之间进行猜测时,我想在渲染下一个成分之前显示两种食物的卡路里。 sleep 2的Java版本是什么?

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


我在这里阅读了一些答案,但它们要么已经过时,要么出现解析错误。我已经尝试过await new Promise(r => setTimeout(r, 2000));并按照here的说明在函数前加上async前缀。

最佳答案

您可以执行此操作(使用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)
    }

关于javascript - sleep 功能的Java语言版本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59849960/

10-12 14:08