({
startTime,
suffix = '',
attributes,
}: ElapsedTimerProps)
| 14 | * Only this component re-renders, not its parents. |
| 15 | */ |
| 16 | export const ElapsedTimer = ({ |
| 17 | startTime, |
| 18 | suffix = '', |
| 19 | attributes, |
| 20 | }: ElapsedTimerProps) => { |
| 21 | const theme = useTheme() |
| 22 | const [elapsedSeconds, setElapsedSeconds] = useState<number>(() => |
| 23 | startTime ? Math.floor((Date.now() - startTime) / 1000) : 0, |
| 24 | ) |
| 25 | |
| 26 | useEffect(() => { |
| 27 | if (!startTime) { |
| 28 | setElapsedSeconds(0) |
| 29 | return |
| 30 | } |
| 31 | |
| 32 | const updateElapsed = () => { |
| 33 | const elapsed = Math.floor((Date.now() - startTime) / 1000) |
| 34 | setElapsedSeconds(elapsed) |
| 35 | } |
| 36 | |
| 37 | // Update immediately |
| 38 | updateElapsed() |
| 39 | |
| 40 | // Then update every second |
| 41 | const interval = setInterval(updateElapsed, 1000) |
| 42 | |
| 43 | return () => clearInterval(interval) |
| 44 | }, [startTime]) |
| 45 | |
| 46 | if (!startTime || elapsedSeconds === 0) { |
| 47 | return null |
| 48 | } |
| 49 | |
| 50 | return ( |
| 51 | <span fg={theme.secondary} attributes={attributes}> |
| 52 | {formatElapsedTime(elapsedSeconds)}{suffix} |
| 53 | </span> |
| 54 | ) |
| 55 | } |
nothing calls this directly
no test coverage detected