How to update a progress bar every second in react?

Viewed 25

I am trying to show a progress bar as a video plays.

To do so I am using setTimeout to invoke the setter function and rerender the component with the updated time.

But I don't think this is the best way to do it. When I put a console.log in this component to check how many times it was being rendered, I saw that it was usually 2 or 4 times.

const ProgressBar = ({ player }) => {
  const [time, setTime] = useState(0);
  let dur = player.getDuration() || 3600;
  console.log(Math.floor(time));

  setTimeout(() => {
    setTime(player.getCurrentTime());
  }, 1000);

  return (
    <Progress value={(time * 100) / dur} size="xs" bg="white" minW="100vw" />
  );
};
1 Answers

Does this solve the case?

const ProgressBar = ({ player }) => {
 let dur = player.getDuration() || 3600;
 console.log(Math.floor(time));

 return (
  <Progress value={(player.getCurrentTime() * 100) / dur} size="xs" bg="white" minW="100vw" />
 );
};
Related