Reputation: 681
I have a count-down timer that when the user presses submit it starts counting down.
I have an if
statement that is reducing the timer 1 second at a time and another function that starts vibrating the phone once the timer starts hitting 3 seconds. Problem is that the vibration starts immediately as soon as the count timer runs.
When I do this.state.seconds
==
or ===
3
the vibration won't work.
If I do an assignment of =3
then the timer count down runs fine but the vibration runs the entire time which means if the timer is 10seconds it'll vibrate for 10 seconds.
What am I doing wrong?
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)
}
Where the timer gets called
<InputCard startTimer={this.startTimer}></InputCard>
Upvotes: 3
Views: 301
Reputation: 3093
Because you make a comparison only once when you press the button. You need to check it on every tick.
startTimer = () => {
this.resetTimer();
this.myInterval = setInterval(() => {
this.vibratePhone();
if (this.state.seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1
}))
}
else {
this.resetTimer()
}
}, 1000);
}
When you tried = 3
, it's not a comparison, it's an assignment that is always true, for example: if (x = 5)
is true, that's why your phone vibrates immediatelly.
Upvotes: 2