Created
February 14, 2020 06:32
-
-
Save pomle/8dae53c57ed0a1e51fe95675aab81743 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useMemo } from "react"; | |
import moment, { Moment, DurationInputArg2 as Unit } from "moment"; | |
export const useLiveTime = (unit: Unit): Moment => { | |
const initial = useMemo(moment, []); | |
const [time, setTime] = useState<Moment>(initial); | |
useEffect(() => { | |
const nextTime = time | |
.clone() | |
.startOf(unit) | |
.add(1, unit); | |
const delay = nextTime.diff(time, "milliseconds"); | |
const timer = setTimeout(setTime, delay, nextTime); | |
return () => clearTimeout(timer); | |
}, [unit, time, setTime]); | |
return time; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment