Reputation: 89
So I've managed to make a working timer and got stuck with another problem. I want to start and pause the timer with a click of a button. The button sets the state, when the state is true, the timer runs and pauses in the false state. But use effect can't be used in conditionals or nested functions, so does the conditional go inside useEffect and where exactly, if I need to also keep the empty array of useeffect?
const [miliseconds, setMiliseconds] = useState(99);
const [start, setStart] = useState(false);
useEffect(() => {
const interval = setInterval(() => {
setMiliseconds(miliseconds => miliseconds - 1);
}, 1000);
}, [])
<button onClick={() => setStart(!start)}>Start</button>
Upvotes: 2
Views: 138
Reputation: 6582
you should approach it this way:
const [miliseconds, setMiliseconds] = useState(99);
const [start, setStart] = useState(false);
useEffect(() => {
const interval = setInterval(() => {
setMiliseconds(miliseconds => start ? miliseconds + 1 : miliseconds);
}, 1000);
return () => { // <- clear your interval
clearInterval(interval);
}
}, [start]) // <- add start as dependency
<button onClick={() => setStart(!start)}>Start</button>
This way when start is true your timer counts upward and when it's false it stops, you can decide if you want to stop or countdown or whatever
The only thing to remember is to use start
variable and decide based on its value in the setInterval
callback function
Upvotes: 4