reactjs - setInterval 在本机反应中无法与异步功能一起使用
问题描述
我只是在学习本机反应,我正在尝试录制视频并在屏幕上显示剩余的视频持续时间。
我正在使用以下代码:
setInterval (() => {
this.setState ({progress: progress * 2});
}, 1000);
var video = await this.camera.recordAsync ({
mute: true,
quality: '480p',
maxDuration: this.state.max_duration,
});
但是视频录制得非常好,但 setiInterval 已停止工作。如何在 a 中运行 setInterval async funtion
?请帮忙..
解决方案
JavaScript/ReactJS/React-Native 没有原生睡眠功能。由于在 ES2018 中实现了 Promise 和 async/await,您可以这样做来执行 setTimeout/setInterval:
为异步函数设置 setInterval:
setInterval(async () => {
await print("waiting")
}, 2000);
(也试试这个)您可以使函数递归。这样,一旦函数完成,您就可以开始下一次迭代的超时。
async function doSomething() {
//code to run on a interval
setTimeout(doSomething, 2000); // <------------------
}
setTimeout(doSomething, 2000);
为异步函数设置 setTimeout,如睡眠函数:
首先把它作为一个函数放在你的代码中
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
现在在 async 函数中使用它:
await sleep(2000)
您也可以使用它
sleep(500).then(() => {
console.log("waiting");
})
推荐阅读
- python - 获取与 Outlook 格式相同的 Outlook 电子邮件 [使用 python]
- c++ - 这是将graphviz用作库的正确方法吗?
- python - 如何使用 Tensorflow 2/Keras 保存和恢复训练具有多个模型部分的 GAN
- python - 无法交互列表
- javascript - 仅当它与 $auth 和 vuejs (nuxt) 一起存在时才显示信息
- python - 如何匹配语句中的变量?
- wordpress - 从所有帖子中获取 ACF 转发器字段值,按子字段排序
- php - NGINX 和 PHP,TLS 版本
- android - 配套设备配对:是否需要启用定位服务?
- artifactory - 是否可以从我们自己的 Artifactory 存储库同步到 Maven Central?