I have a timer using setInterval()in the React component, and I'm not sure what is the best way to start and stop this interval regarding usage state. I ran into some asynchronous problems.
Let's say I have a set of links in my React component that display and execute a callback penalty:
let links = [10, 50, 100, 500, 1000].map((num) => {
return(
<Link key={num} onClick={(e) => this.switchNums(num)} to={`/somePath/${num}`}>{num}</Link>
)
})
Here's the function switchNums()where I want it to reset an existing timer:
switchNums(num){
this.stopTimer()
this.reset(num)
}
Here startTimer(), stopTimer()and reset():
startTimer(){
if(!this.state.timerId){
let timerId = setInterval(()=>{
let timer = this.state.timer + 1
this.setState({
timer: timer,
timerId: timerId
})
}, 1000)
}
}
stopTimer(){
clearInterval(this.state.timerId)
this.setState({timerId:null})
}
reset(size){
this.setState({
gameOver: false,
counter: 0,
correct: 0,
numbers: this.getRandomNumbers(size),
timer: 0
}, this.startTimer())
}
, , if startTimer(). , setState(). ( , ) , , , .
- ? , setState setInterval ( ?), ?