1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import {useCallback, useEffect, useRef, useState} from "react";
interface IProps { count: number; }
type Fnc = () => void; const noop = () => { };
export function useTimeDown({count}: IProps): [number, Fnc] { const [time, setTime] = useState<number>(count) const tickRef = useRef<Fnc>(noop); const tick = useCallback(() => { if (time > 0) { setTime(time - 1); } }, [time]); useEffect(() => { tickRef.current = tick; }) useEffect(() => { tickRef.current = tick; const timerId = window.setInterval(() => tickRef.current(), 1000); return () => window.clearInterval(timerId); }, [tick]) const restart = () => setTime(count);
return [time, restart];
}
|