Last active
July 18, 2023 04:25
-
-
Save JT501/856a5950964502cf54e7be06adb9b2f0 to your computer and use it in GitHub Desktop.
Revisions
-
JT501 revised this gist
Nov 3, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -21,7 +21,7 @@ export const useCountDown: ( useEffect(() => { intervalId.current = setInterval(() => { startCountDown && counter > 0 && setCountDown(counter => counter - 1); }, ms); // Clear interval when count to zero if (counter === 0) clearInterval(intervalId.current); -
JT501 created this gist
Nov 3, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,33 @@ import { useEffect, useRef, useState } from 'react'; export const useCountDown: ( total: number, ms?: number, ) => [number, () => void, () => void, () => void] = ( total: number, ms: number = 1000, ) => { const [counter, setCountDown] = useState(total); const [startCountDown, setStartCountDown] = useState(false); // Store the created interval const intervalId = useRef<number>(); const start: () => void = () => setStartCountDown(true); const pause: () => void = () => setStartCountDown(false); const reset: () => void = () => { clearInterval(intervalId.current); setStartCountDown(false); setCountDown(total); }; useEffect(() => { intervalId.current = setInterval(() => { startCountDown && counter > 0 && setCountDown(countDown => countDown - 1); }, ms); // Clear interval when count to zero if (counter === 0) clearInterval(intervalId.current); // Clear interval when unmount return () => clearInterval(intervalId.current); }, [startCountDown, counter, ms]); return [counter, start, pause, reset]; };