2024-06-26 19:33:38 +00:00
|
|
|
import { useRef, useCallback, useEffect } from 'react';
|
|
|
|
|
|
|
|
export const useTimeout = () => {
|
|
|
|
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
|
2024-07-01 15:52:01 +00:00
|
|
|
const callbackRef = useRef<() => void>();
|
2024-06-26 19:33:38 +00:00
|
|
|
|
|
|
|
const set = useCallback((callback: () => void, delay: number) => {
|
|
|
|
if (timeoutRef.current) {
|
|
|
|
clearTimeout(timeoutRef.current);
|
|
|
|
}
|
|
|
|
|
2024-07-01 15:52:01 +00:00
|
|
|
callbackRef.current = callback;
|
2024-06-26 19:33:38 +00:00
|
|
|
timeoutRef.current = setTimeout(callback, delay);
|
|
|
|
}, []);
|
|
|
|
|
2024-07-01 15:52:01 +00:00
|
|
|
const delay = useCallback((delay: number) => {
|
|
|
|
if (timeoutRef.current) {
|
|
|
|
clearTimeout(timeoutRef.current);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!callbackRef.current) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
timeoutRef.current = setTimeout(callbackRef.current, delay);
|
|
|
|
}, []);
|
|
|
|
|
2024-06-26 19:33:38 +00:00
|
|
|
const cancel = useCallback(() => {
|
|
|
|
if (timeoutRef.current) {
|
|
|
|
clearTimeout(timeoutRef.current);
|
|
|
|
timeoutRef.current = undefined;
|
2024-07-01 15:52:01 +00:00
|
|
|
callbackRef.current = undefined;
|
2024-06-26 19:33:38 +00:00
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(
|
|
|
|
() => () => {
|
|
|
|
cancel();
|
|
|
|
},
|
|
|
|
[cancel],
|
|
|
|
);
|
|
|
|
|
2024-07-01 15:52:01 +00:00
|
|
|
return [set, cancel, delay] as const;
|
2024-06-26 19:33:38 +00:00
|
|
|
};
|