MCPcopy Create free account
hub / github.com/QuarkGluonPlasma/react-course-code / useCountdown

Function useCountdown

ahooks-hook/src/useCountdown.ts:40–77  ·  view source on GitHub ↗
(options: Options = {})

Source from the content-addressed store, hash-verified

38};
39
40const useCountdown = (options: Options = {}) => {
41 const { leftTime, targetDate, interval = 1000, onEnd } = options || {};
42
43 const memoLeftTime = useMemo<TDate>(() => {
44 return leftTime && leftTime > 0 ? Date.now() + leftTime : undefined;
45 }, [leftTime]);
46
47 const target = 'leftTime' in options ? memoLeftTime : targetDate;
48
49 const [timeLeft, setTimeLeft] = useState(() => calcLeft(target));
50
51 const onEndRef = useRef(onEnd);
52 onEndRef.current = onEnd;
53
54 useEffect(() => {
55 if (!target) {
56 setTimeLeft(0);
57 return;
58 }
59
60 setTimeLeft(calcLeft(target));
61
62 const timer = setInterval(() => {
63 const targetLeft = calcLeft(target);
64 setTimeLeft(targetLeft);
65 if (targetLeft === 0) {
66 clearInterval(timer);
67 onEndRef.current?.();
68 }
69 }, interval);
70
71 return () => clearInterval(timer);
72 }, [target, interval]);
73
74 const formattedRes = useMemo(() => parseMs(timeLeft), [timeLeft]);
75
76 return [timeLeft, formattedRes] as const;
77};
78
79export default useCountdown;

Callers

nothing calls this directly

Calls 4

useStateFunction · 0.90
useEffectFunction · 0.90
calcLeftFunction · 0.85
parseMsFunction · 0.85

Tested by

no test coverage detected