javascript - 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.
解决方案
您可以这样做(使用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)
}
推荐阅读
- python - ImportError:尝试安装包时没有名为“打字”的模块
- android - MediaPlayer.setDataSource() 在 Play 商店发布新版本后抛出 IOException
- python - Python OpenCV将轮廓保存为新图像
- php - Symfony 5 中实体的关系
- c++ - 使用 cmake、mingw 的 C++ 中的 MySQL 和 MariaDB 库
- azure - 使用“Microsoft.Azure.KeyVault”SDK 的客户端代码如何设法让 Azure AD 令牌通过 Azure keyvault 进行身份验证以检索机密?
- python - 使用具有可变数量参数的函数字典 - 我可以在这里使用 partial 吗?
- node.js - 当我尝试登录时 Auth0 返回错误
- casting - 包含项目的 const-propagation
- flutter - 颤振初始化失败