Home > Enterprise >  Trouble getting React countdown timer to stop
Trouble getting React countdown timer to stop

Time:10-29

I'm new to React, but I found and modified a countdown timer to work for my purposes. However, I can't figure out how to get the timer to stop. I just want the output to read "0:00" when it finishes.

So I'm not including the beginning of my component that sets the amount of time, but here's the rest:

  const timeBetween = targetTime - currentTime;
  const seconds = Math.floor((timeBetween / 1000) % 60);
  const minutes = Math.floor((timeBetween / 1000 / 60) % 60);

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(Date.now());
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <>
      <div className="content2">
        <p style={{ color: "white" }}>We start in:</p>
        <p style={{ color: "white" }}>
          <span>{`${minutes}:${seconds < 10 ? "0" : ""}${seconds}`}</span>
        </p>
      </div>
    </>
  );

CodePudding user response:

You are on the right track, you just need to add a check condition before you setCurrentTime

Just check if targetTime has already surpassed current time and remove the interval if the time has passed.

const interval = setInterval(() => {
  if (targetTime > new Date()) {
    setCurrentTime(Date.now());
  } else {
    clearInterval(interval);
  }
}, 1000);

Here is a working stakblitz example

  • Related