I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: "",
};
}
ponentDidMount() {
//current time
setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000)
}
stopTimer = () => {
clearInterval(this.state.currentTime)
}
render() {
return (
<div>
<h4>Current time: {this.state.currentTime}</h4>
<Button onClick={this.stopTimer}>Stop timer</Button>
</div>
)
}
}
I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: "",
};
}
ponentDidMount() {
//current time
setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000)
}
stopTimer = () => {
clearInterval(this.state.currentTime)
}
render() {
return (
<div>
<h4>Current time: {this.state.currentTime}</h4>
<Button onClick={this.stopTimer}>Stop timer</Button>
</div>
)
}
}
Share
Improve this question
asked Dec 15, 2020 at 19:16
user14681827user14681827
1533 silver badges14 bronze badges
1
- 1 Does this answer your question? setInterval in a React app – Emile Bergeron Commented Dec 15, 2020 at 20:22
2 Answers
Reset to default 6setInterval()
result is the intervalID
and you should use this for clearInterval()
.
this.state = {
...
intervalId: ""
};
...
const intervalId = setInterval(() => {
...
}, 1000);
this.setState({ intervalId });
...
clearInterval(this.state.intervalId);
You are using the clearInterval on wrong variable . You should do this.
I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: "",
intervalId: ""
};
}
ponentDidMount() {
//current time
const intervalId = setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000);
this.setState({intervalId})
}
stopTimer = () => {
if (this.state.intervalId) {
clearInterval(this.state.intervelId)
}
}
render() {
return (
<div>
<h4>Current time: {this.state.currentTime}</h4>
<Button onClick={this.stopTimer}>Stop timer</Button>
</div>
)
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744727036a4590242.html
评论列表(0条)