()
| 32 | * setTimeout('message', () => console.log('Second'), 2000) // Cancels first, schedules second |
| 33 | */ |
| 34 | export function useTimeout() { |
| 35 | const timeoutsRef = useRef<Map<string, NodeJS.Timeout>>(new Map()) |
| 36 | |
| 37 | const setTimeout = useCallback((key: string, callback: () => void, delay: number) => { |
| 38 | const timeouts = timeoutsRef.current |
| 39 | |
| 40 | // Clear existing timeout for this key if it exists |
| 41 | const existingTimeout = timeouts.get(key) |
| 42 | if (existingTimeout) { |
| 43 | globalThis.clearTimeout(existingTimeout) |
| 44 | } |
| 45 | |
| 46 | // Set new timeout with automatic cleanup after execution |
| 47 | const timeoutId = globalThis.setTimeout(() => { |
| 48 | callback() |
| 49 | timeouts.delete(key) |
| 50 | }, delay) |
| 51 | timeouts.set(key, timeoutId) |
| 52 | }, []) |
| 53 | |
| 54 | const clearTimeout = useCallback((key?: string) => { |
| 55 | const timeouts = timeoutsRef.current |
| 56 | |
| 57 | if (key) { |
| 58 | // Clear specific timeout |
| 59 | const timeoutId = timeouts.get(key) |
| 60 | if (timeoutId) { |
| 61 | globalThis.clearTimeout(timeoutId) |
| 62 | timeouts.delete(key) |
| 63 | } |
| 64 | } else { |
| 65 | // Clear all timeouts |
| 66 | timeouts.forEach((timeoutId) => { |
| 67 | globalThis.clearTimeout(timeoutId) |
| 68 | }) |
| 69 | timeouts.clear() |
| 70 | } |
| 71 | }, []) |
| 72 | |
| 73 | useEffect(() => { |
| 74 | return () => { |
| 75 | // Clean up all timeouts on unmount |
| 76 | const timeouts = timeoutsRef.current |
| 77 | timeouts.forEach((timeoutId) => { |
| 78 | globalThis.clearTimeout(timeoutId) |
| 79 | }) |
| 80 | timeouts.clear() |
| 81 | } |
| 82 | }, []) |
| 83 | |
| 84 | return { setTimeout, clearTimeout } |
| 85 | } |
no test coverage detected