mirror of
https://github.com/glitch-soc/mastodon.git
synced 2024-11-29 19:40:23 -05:00
e89317d4c1
Co-authored-by: Renaud Chaput <renchap@gmail.com>
30 lines
637 B
TypeScript
30 lines
637 B
TypeScript
import { useRef, useCallback, useEffect } from 'react';
|
|
|
|
export const useTimeout = () => {
|
|
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
|
|
|
|
const set = useCallback((callback: () => void, delay: number) => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
|
|
timeoutRef.current = setTimeout(callback, delay);
|
|
}, []);
|
|
|
|
const cancel = useCallback(() => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
timeoutRef.current = undefined;
|
|
}
|
|
}, []);
|
|
|
|
useEffect(
|
|
() => () => {
|
|
cancel();
|
|
},
|
|
[cancel],
|
|
);
|
|
|
|
return [set, cancel] as const;
|
|
};
|