Skip to content

Commit

Permalink
feat: export the run function and add null type in the delay option
Browse files Browse the repository at this point in the history
  • Loading branch information
immois committed Oct 18, 2023
1 parent 971be7a commit 86e9b98
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions packages/hooks/use-timeout/src/index.ts
Original file line number Diff line number Diff line change
@@ -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<NodeJS.Timeout | null>(null);

Expand All @@ -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(() => {
Expand All @@ -32,5 +39,5 @@ export const useTimeout = (
return () => clear();
}, [delay, run, clear]);

return { clear, reset };
return { clear, reset, run };
};

0 comments on commit 86e9b98

Please sign in to comment.