Reputation: 3
Below is my code. Its giving me result as 0, 1,2 , 4, 8, 16.... Whats wrong with this. I'm new react. import {react,Component} from 'react'
class Timer extends Component{
constructor(props){
super(props);
this.state={
count:0
}
}
updateTime(){
setInterval(() => {
var number=this.state.count+1;
this.setState({ count:number })} , 5000);
}
render(){
this.updateTime()
return(
<div>
<h1>{this.state.count}</h1>
</div>
)
}
}
export default Timer;
However changing the updateTime function as below, is giving expected result
updateTime(){
var number=this.state.count;
setInterval(() => {
number++;
this.setState({ count:number })}, 5000);
}
expected result:- increment number by 1 every 5 sec
Upvotes: 0
Views: 48
Reputation: 1793
Every time the state updates, the render()
function runs. You're calling this.updateTime()
every time render()
runs, which is setting the interval multiple times. After 4 render calls, you've got 4 timers runnning, each incrementing the state.count
by 1 every time. To reduce the number of intervals, just set the interval once:
componentDidMount() {
this.updateTime();
}
Upvotes: 0
Reputation: 32076
Every time you render, you call updateTime()
, which kicks off a new timer.
Only call updateTime()
in componentDidMount
instead of in render
.
Make sure to clear the timer when you unmount:
componentDidMount() {
this.timer = this.updateTime();
}
componentWillUnmount() {
clearInterval(this.timer);
}
updateTime(){
return setInterval(() => {
var number=this.state.count+1;
this.setState({ count:number })
}, 5000);
}
Upvotes: 1