| 44 | * @param delay - Debounce delay in milliseconds (default: 200ms) |
| 45 | */ |
| 46 | export const useEmittLazy = (eventName: string, params: any = null, delay = 150) => { |
| 47 | // If there's already a pending execution, skip this call |
| 48 | if (lazyDebounceMap.has(eventName)) { |
| 49 | const entry = lazyDebounceMap.get(eventName)! |
| 50 | if (entry.isPending) { |
| 51 | return |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Clear existing timer if present |
| 56 | if (lazyDebounceMap.has(eventName)) { |
| 57 | const { timer } = lazyDebounceMap.get(eventName)! |
| 58 | if (timer) { |
| 59 | clearTimeout(timer) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // Set up a new timer |
| 64 | const timer = setTimeout(() => { |
| 65 | emitter.emit(eventName, params) |
| 66 | |
| 67 | // Mark execution as complete |
| 68 | if (lazyDebounceMap.has(eventName)) { |
| 69 | lazyDebounceMap.get(eventName)!.isPending = false |
| 70 | } |
| 71 | }, delay) |
| 72 | |
| 73 | // Store timer information and mark as pending |
| 74 | lazyDebounceMap.set(eventName, { |
| 75 | timer, |
| 76 | isPending: true, |
| 77 | }) |
| 78 | |
| 79 | // Clean up on component unmount |
| 80 | onBeforeUnmount(() => { |
| 81 | if (lazyDebounceMap.has(eventName)) { |
| 82 | const { timer } = lazyDebounceMap.get(eventName)! |
| 83 | if (timer) { |
| 84 | clearTimeout(timer) |
| 85 | } |
| 86 | lazyDebounceMap.delete(eventName) |
| 87 | } |
| 88 | }) |
| 89 | } |