I have made a countdown timer but every time the site is loaded, the timer takes 1.5s to load in from the default 0 values. Is there any way to preload it or make it appear instantly?
function Timer() {
const [days, setDays] = useState(0);
const [hours, setHours] = useState(0);
const [minutes, setMinutes] = useState(0);
const [seconds, setSeconds] = useState(0);
const deadline = "February, 17, 2023";
const getTime = () => {
const time = Date.parse(deadline) - Date.now();
setDays(Math.floor(time / (1000 * 60 * 60 * 24)));
setHours(Math.floor((time / (1000 * 60 * 60)) % 24));
setMinutes(Math.floor((time / 1000 / 60) % 60));
setSeconds(Math.floor((time / 1000) % 60));
};
useEffect(() => {
const interval = setInterval(() => getTime(deadline), 1000);
return () => clearInterval(interval);
}, []);
CodePudding user response:
It's because the first time you evaluate the timer is after the initial 1s delay. The easiest fix would be to call getTime
before creating the interval:
useEffect(() => {
// This will run after the component mounts
getTime();
// This will then run every second afterwards
const interval = setInterval(() => getTime(), 1000);
return () => clearInterval(interval);
}, []);