1
0
mirror of https://github.com/funamitech/mastodon synced 2024-12-12 05:39:02 +09:00
YuruToot/app/javascript/flavours/glitch/hooks/useTimeout.ts
Eugen Rochko dcfd39991b [Glitch] Change hover cards to not appear until the mouse stops in web UI
Port b728c0e8ce to glitch-soc

Signed-off-by: Claire <claire.github-309c@sitedethib.com>
2024-07-01 20:50:26 +02:00

45 lines
1018 B
TypeScript

import { useRef, useCallback, useEffect } from 'react';
export const useTimeout = () => {
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
const callbackRef = useRef<() => void>();
const set = useCallback((callback: () => void, delay: number) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
callbackRef.current = callback;
timeoutRef.current = setTimeout(callback, delay);
}, []);
const delay = useCallback((delay: number) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
if (!callbackRef.current) {
return;
}
timeoutRef.current = setTimeout(callbackRef.current, delay);
}, []);
const cancel = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
callbackRef.current = undefined;
}
}, []);
useEffect(
() => () => {
cancel();
},
[cancel],
);
return [set, cancel, delay] as const;
};