Skip to content

Commit

Permalink
feat: add reset function
Browse files Browse the repository at this point in the history
  • Loading branch information
immois committed Oct 18, 2023
1 parent 0680e4f commit 971be7a
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions packages/hooks/use-timeout/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
import { useEffect, useRef } from 'react';
import { useCallback, useEffect, useRef } from 'react';

type UseTimeout = (cb: () => void, delay: number) => () => void;

export const useTimeout: UseTimeout = (cb, delay) => {
export const useTimeout = (
cb: () => void,
delay: number
): { clear: () => void; reset: () => void } => {
const savedCallback = useRef(cb);
const id = useRef<NodeJS.Timeout | null>(null);

const clearId = () => {
const clear = useCallback(() => {
if (!id.current) return;
clearTimeout(id.current);
id.current = null;
};
}, []);

const run = useCallback(() => {
const tick = () => savedCallback.current();
id.current = setTimeout(tick, delay);
}, [delay]);

const reset = useCallback(() => {
clear();
run();
}, [run, clear]);

useEffect(() => {
savedCallback.current = cb;
}, [cb]);

useEffect(() => {
const tick = () => savedCallback.current();
id.current = setTimeout(tick, delay);
return () => clearId();
}, [delay]);
run();
return () => clear();
}, [delay, run, clear]);

return clearId;
return { clear, reset };
};

0 comments on commit 971be7a

Please sign in to comment.