我有一个倒计时计时器,当用户按下提交时它开始倒计时。
我有一个 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/