diff --git a/packages/hooks/use-timeout/src/index.ts b/packages/hooks/use-timeout/src/index.ts index 49dc94c..e56e472 100644 --- a/packages/hooks/use-timeout/src/index.ts +++ b/packages/hooks/use-timeout/src/index.ts @@ -1,9 +1,15 @@ import { useCallback, useEffect, useRef } from 'react'; +/** + * A React hook for handling timeouts + * @param cb The callback function to be executed after the specified timeout. + * @param delay The duration of the timeout in milliseconds. + * @see https://raddix.website/docs/use-timeout + */ export const useTimeout = ( cb: () => void, - delay: number -): { clear: () => void; reset: () => void } => { + delay: number | null +): { clear: () => void; reset: () => void; run: () => void } => { const savedCallback = useRef(cb); const id = useRef(null); @@ -14,8 +20,9 @@ export const useTimeout = ( }, []); const run = useCallback(() => { - const tick = () => savedCallback.current(); - id.current = setTimeout(tick, delay); + if (id.current) return; + if (delay === null) return; + id.current = setTimeout(() => savedCallback.current(), delay); }, [delay]); const reset = useCallback(() => { @@ -32,5 +39,5 @@ export const useTimeout = ( return () => clear(); }, [delay, run, clear]); - return { clear, reset }; + return { clear, reset, run }; };