1

I am receiving a timestamp in milliseconds which is the reamining time left for an event to start. I need to use that timestamp to build a countdown timer having days , hours , minutes and seconds. I am a beginner to react and javascript. This is what I have tried but, this code does not seem to convert it properly. Can anyone please helpe me understand where I am going wrong and how I can fix this?

 const [timeRemaining, settimeRemaining] = useState(props.timeRemaining);
  const [days, setdays] = useState(0);
  const [hours, sethours] = useState(0);
  const [mins, setmins] = useState(0);
  const [secs, setsecs] = useState(0);

  // countdown timer
  useEffect(() => {
    if (!timeRemaining) return;
    const intervalId = setInterval(() => {
      settimeRemaining(timeRemaining - 1);
      setsecs(timeRemaining / 1000);
      setmins(secs / 60);
      sethours(mins / 60);
      setdays(hours / 24);
    }, 1000);
    return () => clearInterval(intervalId);
  }, [timeRemaining]);

1 Answers1

0

You are having 2 issues:

  • Convert time incorrectly

  • If you pass props is a miliseconds. You should set remain timing sub with 1000 (coordinate with time interval).

    const [timeRemaining, settimeRemaining] = useState(props.timeRemaining);
     const [days, setdays] = useState(0);
     const [hours, sethours] = useState(0);
     const [mins, setmins] = useState(0);
     const [secs, setsecs] = useState(0);
    
     // countdown timer
     useEffect(() => {
         if (timeRemaining < 0) return;
         const intervalId = setInterval(() => {
             settimeRemaining(timeRemaining - 1000);
    
    
             setsecs(Math.floor((timeRemaining / 1000) % 60));
             setmins(Math.floor((timeRemaining / 1000 / 60) % 60));
             sethours(Math.floor((timeRemaining / 1000 / 60 / 60) % 24));
             setdays(Math.floor((timeRemaining / 1000 / 60 / 60 / 24)));
         }, 100);
         return () => clearInterval(intervalId);
     }, [timeRemaining]);
    
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18