Reputation: 5647
I've been working on improving my React skills by creating a pomodoro timer app. For some reason I can't seem to get clearInterval
working:
startTimer() {
const { started } = this.state;
var timer;
if (!started) {
timer = setInterval(this.countdown, 1000);
this.setState({ started: true });
}
else {
clearInterval(timer);
this.setState({ started: false });
}
}
No console errors. Can confirm that it's definitely running that part of the conditional statement (when I log this.state.started
it shows false
). The timer just keeps ticking and doesn't actually stop.
Rest of the code:
import React, { Component } from 'react';
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
secs: 60,
started: false
};
this.startTimer = this.startTimer.bind(this);
this.countdown = this.countdown.bind(this);
}
countdown() {
this.setState({ secs: this.state.secs - 1});
}
startTimer() {
const { started } = this.state;
var timer;
if (!started) {
timer = setInterval(this.countdown, 1000);
this.setState({ started: true });
}
else {
clearInterval(timer);
this.setState({ started: false });
}
}
render() {
const { secs } = this.state;
console.log('secs:', secs)
console.log('started:', this.state.started);
return (
<div className='timer' onClick={this.startTimer}>
<h2>Session</h2>
<h1>{this.props.session}:{secs == 60 ? '00': secs}</h1>
</div>
);
}
}
export default Timer;
Upvotes: 2
Views: 9936
Reputation: 1493
if you aren't trying to create a class
if(condition_is_true){
const checkUntilConditionIsFalse = setInterval(() => {
if (condition_is_false) {
clearInterval(checkUntilConditionIsFalse);
}
}, 1000);
}
Upvotes: 0
Reputation: 62743
Initialize this.timer
in the constructor. Then create the setInterval
and assign it to this.timer
, which will allow you to clear it later.
import React, { Component } from 'react';
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
secs: 60,
started: false
};
this.timer = null;
this.startTimer = this.startTimer.bind(this);
this.countdown = this.countdown.bind(this);
}
countdown() {
this.setState({ secs: this.state.secs - 1});
}
startTimer() {
const { started } = this.state;
if (!started) {
this.timer = setInterval(this.countdown, 1000);
this.setState({ started: true });
}
else {
clearInterval(this.timer);
this.setState({ started: false });
}
}
render() {
const { secs } = this.state;
console.log('secs:', secs)
console.log('started:', this.state.started);
return (
<div className='timer' onClick={this.startTimer}>
<h2>Session</h2>
<h1>{this.props.session}:{secs == 60 ? '00': secs}</h1>
</div>
);
}
}
export default Timer;
Upvotes: 5