I am learning React JS and I started building a Pomodoro clock. I do not understand how to start a specified interval upon clicking a button and stopping the timer upon clicking a separate button. When I click "play" the timer stalls at 24:059. When I click the same button, it goes to 24:058 and jumps back to 24:059 then repeats. When I click it again, it goes to 24:057, etc.
When I remove the switch(seconds)
condition in decreaseTimer()
and simply insert setSeconds((seconds) => seconds - 1);
the seconds decrement by 1 as expected. How do I fix this issue? I appreciate all the help and advice here. Thank you!
PomoTimer.js
import { useEffect, useState } from "react";
const PomoTimer = (props) => {
const [seconds, setSeconds] = useState(0);
const [intervalId, setIntervalId] = useState("");
const [isSession, setSession] = useState(true);
const startTimer = () => {
let newIntervalId = setInterval(decreaseTimer, 1000);
setIntervalId((intervalId) => newIntervalId);
};
const stopTimer = () => {
clearInterval(intervalId);
};
const decreaseTimer = () => {
switch (seconds) {
case 0:
props.onTimerMinuteChange(props.timerMinute - 1);
setSeconds((seconds) => 59);
break;
default:
setSeconds((seconds) => seconds - 1);
break;
}
};
const resetTimer = () => {
clearInterval(intervalId);
props.resetTimer();
props.onPlayChange(false);
setSeconds(0);
};
return (
<section>
<section>
{/* <h4>{session === true ? "Session" : "Break"}</h4> */}
<span>{props.timerMinute}</span>
<span>:</span>
<span>{seconds === 0 ? "00" : "0" + seconds}</span>
</section>
<section>
<button onClick={startTimer}>Play</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Refresh</button>
</section>
</section>
);
};
export default PomoTimer;