import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const [timerHours, setTimerHours] = useState('00');
const [timerMinutes, setTimerMinutes] = useState('00');
const [timerSeconds, setTimerSeconds] = useState('00');
const startTimer = (duration) => {
setInterval(() => {
var seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
if (hours === 0 && minutes === 0) {
clearInterval();
}
else {
setTimerHours(hours);
setTimerMinutes(minutes);
setTimerSeconds(seconds);
}
}, 1000)
}
useEffect(() => {
startTimer(80214523);
return () => {
clearInterval()
}
});
return (
<div className="App">
{timerHours} : {timerMinutes} : {timerSeconds}
</div>
);
}
code structure like this. There is no problem getting the hour, minute and second information. The countdown is not working.
Example : https://codesandbox.io/s/zealous-aryabhata-r1dwo?file=/src/App.js:0-1101
Your problem is that the useeffect hook is run every time the state is updated, then you countdown is started with same start point all the time because you use a constant
I found an example here https://www.digitalocean.com/community/tutorials/react-countdown-timer-react-hooks