I start using react to create a timer. I use "timerState" in the state for checking the status of the interval. Then I create function "startStop" to toggle start and stop the interval base on the "timerState". Every time I click "startStop" button, it adds a new interval but not clear the last one. Where is the problem? Here's the code:
class App extends Component {
state = {
breakLength: 5,
sessionLength: 25,
timerState: "paused",
}
startStop() {
var mins = this.state.sessionLength
var secs = mins * 60
var minutes = document.getElementById("minutes")
var seconds = document.getElementById("seconds")
function getminutes() {
//minutes is seconds divided by 60, rounded down
return mins = Math.floor(secs / 60)
}
function getseconds() {
//take minutes remaining (as seconds) away
//from total seconds remaining
return secs - Math.round(mins * 60)
}
function decrement() {
function appendZero(number) {
if (number <= 9)
return "0" + number
else
return number
}
minutes.innerHTML = appendZero(getminutes())
seconds.innerHTML = appendZero(getseconds())
secs = secs - 1
}
if (this.state.timerState = "paused") {
this.setState({
timerState: setInterval(() => decrement(), 1000)
}, function () {console.log(this.state.timerState)})
}
else if (this.state.timerState !== "paused") {
clearInterval(this.state.timerState)
this.setState({
timerState: "paused"
}, function () {console.log(this.state.timerState)})
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…