ElapsedTime.tsx 946 B

1234567891011121314151617181920212223
  1. import React, { FC, useState, useEffect } from 'react';
  2. import { useInterval } from 'react-use';
  3. import { Time, TimeProps } from './Time';
  4. const INTERVAL = 150;
  5. export interface ElapsedTimeProps extends Omit<TimeProps, 'timeInMs'> {
  6. // Use this to reset the timer. Any value is allowed just need to be !== from the previous.
  7. // Keep in mind things like [] !== [] or {} !== {}.
  8. resetKey?: any;
  9. }
  10. export const ElapsedTime: FC<ElapsedTimeProps> = ({ resetKey, humanize, className }) => {
  11. const [elapsed, setElapsed] = useState(0); // the current value of elapsed
  12. // hook that will schedule a interval and then update the elapsed value on every tick.
  13. useInterval(() => setElapsed(elapsed + INTERVAL), INTERVAL);
  14. // this effect will only be run when resetKey changes. This will reset the elapsed to 0.
  15. useEffect(() => setElapsed(0), [resetKey]);
  16. return <Time timeInMs={elapsed} className={className} humanize={humanize} />;
  17. };