ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Saturday, December 17, 2022

[FIXED] How do I remove the delay the countdown timer?

 December 17, 2022     date, javascript, react-hooks, reactjs   

Issue

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);
  }, []);

Solution

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);
}, []);


Answered By - gerrod
Answer Checked By - - Senaida (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix