Home > Back-end >  I want to restart a circular progress bar after 30 seconds
I want to restart a circular progress bar after 30 seconds

Time:11-25

const useProgress = (maxTimeInSeconds = 30) => {
    const [elapsedTime, setElapsedTime] = useState(0);
    const [progress, setProgress] = useState(0);

    useEffect(() => {
      const intervalId = setInterval((callback) => {
        if (progress < 1) {
          setElapsedTime((t) => t   1);
        }
      }, 1000);

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

    useEffect(() => {
      setProgress(elapsedTime / maxTimeInSeconds);
      console.log(elapsedTime);
    }, [elapsedTime]);

    return progress;
  };
  const progress = useProgress();

Here I have implemented logic to move the circular progress bar for 30 seconds. What I want to do is restart the progress after 30 seconds and keep it in the loop for 30 seconds.

CodePudding user response:

progress does not need to be a state atom since it's always unambiguously calculable from the elapsed time and max time.

Using the modulo (remainder) operator you can have the observed progress always loop back to 0 after the maximum time.

const useProgress = (maxTimeInSeconds = 30) => {
  const [elapsedTime, setElapsedTime] = useState(0);
  useEffect(() => {
    const intervalId = setInterval(() => {
      setElapsedTime((t) => t   1);
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);
  return (elapsedTime % maxTimeInSeconds) / maxTimeInSeconds;
};
const progress = useProgress();
  • Related