Search code examples
javascriptreactjstimeruse-state

ReactJS - Using setInterval for decreasing timer


I am trying to create a timer application in react. The app works by calling a setInterval timer when the user clicks a button.

const [timer, setTimer] = useState(1500)    // 25 minutes
const [start, setStart] = useState(false)

const onClick = () => {
    if (!start) {
        var tick = setInterval(() => {
            setStart(true)
            if (timer < 0) {
                clearInterval(tick)
            }
            setTimer(timer => timer - 1)
            console.log(timer)
            
        }, 1000)
    }
}

Even though the timer is decreasing every second, console.log(timer) still prints out 1500 and does not decrease. I am not able to stop the timer thereafter.


Solution

  • The set function is asynchronous, so the console.log does not have the new value yet.

    Put the log inside the function setTimer:

    ...
    setTimer(timer => {
        console.log(timer - 1)
        return timer - 1;
    })
    ...