From d35060a6a7de86a137eb754e6bf6d79787712e34 Mon Sep 17 00:00:00 2001 From: UIUX Lab Date: Thu, 29 Aug 2024 10:10:14 +0800 Subject: [PATCH] update hook useInterval --- src/utils/hooks/useInterval.js | 39 ++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/src/utils/hooks/useInterval.js b/src/utils/hooks/useInterval.js index 410dfdc..2024b5d 100644 --- a/src/utils/hooks/useInterval.js +++ b/src/utils/hooks/useInterval.js @@ -6,37 +6,48 @@ const App = () => { const [count, setCount] = useState(0); - useInterval(() => { + const { startTimer, stopTimer } = useInterval(() => { setCount(count + 1); }, 1000); return ( -
+
{count}
); }; */ -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useCallback } from "react"; const useInterval = (fn, delay) => { const ref = useRef(null); + + const intervalIdRef = useRef(null); + const startTimer = useCallback(() => { + intervalIdRef.current = setInterval(() => { + ref.current && ref.current(); + }, delay); + }, [ref]); + + const stopTimer = useCallback(() => { + clearInterval(intervalIdRef.current); + intervalIdRef.current = null; + }, []); useEffect(() => { ref.current = fn; }, [fn]); useEffect(() => { - function tick() { - ref.current && ref.current(); - } - - if (delay !== null && delay > 0) { - let id = setInterval(tick, delay); - return () => clearInterval(id); - } else { - tick(); - } - }, [delay]); + startTimer(); + return () => stopTimer(); + }, []); + + + return { + startTimer, + stopTimer + }; + }; export default useInterval;