javascript - 当计时器达到特定数字时 react 振动手机

标签 javascript reactjs react-native

我有一个倒计时计时器,当用户按下提交时它开始倒计时。
我有一个 if 语句,它一次减少计时器 1 秒,另一个函数在计时器开始达到 3 秒后开始振动手机。问题是,一旦计数计时器运行,振动就会立即开始。

当我执行 this.state.seconds ===== 3 时,振动不会不工作。 如果我执行 =3 的分配,则计时器倒计时运行正常,但振动会一直运行,这意味着如果计时器为 10 秒,它将振动 10 秒。

我做错了什么?

   resetTimer = () => {
    if(this.myInterval) {
      clearInterval(this.myInterval);
      this.setState({ seconds: this.props.exerciseData.rests });
    }
  }

  vibratePhone = () => {

    if (this.state.seconds === 3) {
      Vibration.vibrate(4 * 1000)
    }
  }

  startTimer = () => {
    this.vibratePhone();
    this.resetTimer();
    this.myInterval = setInterval(() => {

      if (this.state.seconds > 0) {
        this.setState(({ seconds }) => ({
          seconds: seconds - 1
        }))
        
      }
      else {
        this.resetTimer()
      }
    }, 1000)
  }

定时器被调用的地方

<InputCard startTimer={this.startTimer}></InputCard>

最佳答案

因为你只在按下按钮时进行一次比较。您需要在每次报价时检查它。

startTimer = () => {
  this.resetTimer();

  this.myInterval = setInterval(() => {
    this.vibratePhone();

    if (this.state.seconds > 0) {
      this.setState(({ seconds }) => ({
        seconds: seconds - 1
      }))    
    }
    else {
      this.resetTimer()
    }
  }, 1000);
}

当你尝试 = 3 时,它不是比较,它是一个始终为真的赋值,例如:if (x = 5) 为真,这就是为什么您的手机立即振动。

关于javascript - 当计时器达到特定数字时 react 振动手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65413733/

相关文章:

javascript - 为什么 'keydown'/'keyup' 在第一次按键时没有触发?

react-native - createBottomTabNavigator 中的初始路线有问题

css - 我怎样才能使这个容器作为页脚出现在屏幕上,并使用 React Native 中的 css?

reactjs - useSWR 未加载数据。数据保持加载状态

node.js - 使用 React 从 nodejs 服务器获取图像

reactjs - 无法在 React 中使用 fetch 从 ipify 获取响应

android - React Native ./gradlew assembleRelease assembleAndroidTest失败: “More than one file found with OS independent path”

javascript - 如何在标题和图标之间添加空格? react 中

javascript - 谷歌地图 : set StyledMapType with Terrain

javascript - 奇怪的链接到/未定义 AngularJS