File size: 883 Bytes
9705b6c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import { useEffect, useRef } from 'react';
type TUseTimeoutParams = {
callback: (error: string | number | boolean | null) => void;
delay?: number;
};
type TTimeout = ReturnType<typeof setTimeout> | null;
function useTimeout({ callback, delay = 400 }: TUseTimeoutParams) {
const timeout = useRef<TTimeout>(null);
const callOnTimeout = (value?: string) => {
// Clear existing timeout
if (timeout.current !== null) {
clearTimeout(timeout.current);
}
// Set new timeout
if (value) {
console.log(value);
timeout.current = setTimeout(() => {
callback(value);
}, delay);
}
};
// Clear timeout when the component unmounts
useEffect(() => {
return () => {
if (timeout.current !== null) {
clearTimeout(timeout.current);
}
};
}, []);
return callOnTimeout;
}
export default useTimeout;
|