Reputation: 49
I would like at the start of startStop(), "secs" would equal "remaining". then set state "remaining" to equal "secs" at the end of the interval. However, the "secs" does update each 1000 millisecond, but setState for "remaining" does not actually update. Does it has to do anything with secs only update within the nested function decrement()? How to get "remaining" to update?
class App extends Component {
state = {
timerState: "paused"
remaining: 1500,
}
startStop() {
var secs = this.state.remaining
function getminutes()
return Math.floor(secs / 60)
}
function getseconds() {
return secs - Math.round(getminutes() * 60)
}
function appendZero(number) {
if (number <= 9)
return "0" + number
else
return number
}
const decrement = () => {
document.getElementById("minutes").innerHTML = appendZero(getminutes())
document.getElementById("seconds").innerHTML = appendZero(getseconds())
secs = secs - 1
}
if (this.state.timerState === "paused") {
this.setState({
timerState: setInterval(() => decrement(), 1000)
},
this.setState({
remaining: secs
})
}
else if (this.state.timerState !== "paused") {
clearInterval(this.state.timerState)
this.setState({
timerState: "paused"
})
}
this.setState({
remaining: secs
})
}
Upvotes: 0
Views: 80
Reputation: 49
Got it to work. I moved the setState to increment() as below:
const decrement = () => {
document.getElementById("minutes").innerHTML = appendZero(getminutes())
document.getElementById("seconds").innerHTML = appendZero(getseconds())
secs = secs - 1
this.setState({
remaining: secs
})
}
Still don't understand why it doesn't work if setState() at the end of startStop() as my original question?
Upvotes: 1
Reputation: 5937
Change this
this.setState({
timerState: setInterval(() => decrement(), 1000)
},
this.setState({
remaining: secs
})
to:
this.setState({
timerState: setInterval(() => decrement(), 1000),
remaining: secs
})
Upvotes: 1