mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-21 10:50:14 +01:00
40 lines
906 B
TypeScript
40 lines
906 B
TypeScript
|
|
import { useEffect, useRef } from 'react';
|
||
|
|
|
||
|
|
type TUseTimeoutParams = {
|
||
|
|
callback: (error: string | number | boolean | null) => void;
|
||
|
|
delay?: number | undefined;
|
||
|
|
};
|
||
|
|
type TTimeout = ReturnType<typeof setTimeout> | null;
|
||
|
|
|
||
|
|
function useTimeout({ callback, delay = 400 }: TUseTimeoutParams) {
|
||
|
|
const timeout = useRef<TTimeout>(null);
|
||
|
|
|
||
|
|
const callOnTimeout = (value: string | undefined) => {
|
||
|
|
// 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;
|