首页 > 解决方案 > 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?请帮忙..

标签: reactjstypescriptreact-nativeexpo

解决方案


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

推荐阅读