首页 > 解决方案 > setTimeout 将我的应用程序冻结在本机反应中

问题描述

我正在使用 setTimeout 函数来显示 3.. 2.. 1.. 在开始我的实际功能之前先显示文本

但有时应用程序会在 2 或 1 或 GO 处冻结并直接跳转到实际功能。

我的代码如下:

  setInterval(() => {
      _this.setState({
        timer: _this.state.timer - 1
      })
      if (_this.state.timer == 0) {
        _this.setState({ timer: 'GO' })
      }
    }, 1000)

因此,当计时器为 0 时,每秒都会减少其值,它显示 GO 但我的应用程序正在冻结,谁能帮我解决这个问题谢谢

标签: react-nativesettimeoutsetinterval

解决方案


你可以这样使用。因为 setInterval 和 setState 都是异步的。

let timer = this.state.timer
let interval = setInterval( () => {
  if(typeof timer === "number"){
    timer--;
  }
  if(timer === 0){  //once the timer goes 0 then it clears interval
    clearInterval(interval)   //to clear Interval
    this.setState({ timer: "Go"})
  }else{           
    this.setState({ timer: timer})
  }      
}, 1000)

推荐阅读