Synchronize clock to start of second

This commit is contained in:
Tulir Asokan 2025-01-03 13:50:32 +02:00
parent 0e4addd3fc
commit 6b7945c50b

View file

@ -29,10 +29,13 @@ const currentTimeAdjusted = (tz: string) => {
function ClockElement({ tz }: { tz: string }) { function ClockElement({ tz }: { tz: string }) {
const [time, setTime] = useState(currentTimeAdjusted(tz)) const [time, setTime] = useState(currentTimeAdjusted(tz))
useEffect(() => { useEffect(() => {
const interval = setInterval(() => { let interval: number | undefined
setTime(currentTimeAdjusted(tz)) const updateTime = () => setTime(currentTimeAdjusted(tz))
}, (1000 - Date.now() % 1000)) const timeout = setTimeout(() => {
return () => clearInterval(interval) interval = setInterval(updateTime, 1000)
updateTime()
}, (1001 - Date.now() % 1000))
return () => interval ? clearInterval(interval) : clearTimeout(timeout)
}, [tz]) }, [tz])
return <div>{time}</div> return <div>{time}</div>
} }