| 1 | import { v4 as uuidv4 } from "uuid"; |
| 2 | |
| 3 | export class AutocompleteDebouncer { |
| 4 | private debounceTimeout: NodeJS.Timeout | undefined = undefined; |
| 5 | private currentRequestId: string | undefined = undefined; |
| 6 | |
| 7 | async delayAndShouldDebounce(debounceDelay: number): Promise<boolean> { |
| 8 | // Generate a unique ID for this request |
| 9 | const requestId = uuidv4(); |
| 10 | this.currentRequestId = requestId; |
| 11 | |
| 12 | // Clear any existing timeout |
| 13 | if (this.debounceTimeout) { |
| 14 | clearTimeout(this.debounceTimeout); |
| 15 | } |
| 16 | |
| 17 | // Create a new promise that resolves after the debounce delay |
| 18 | return new Promise<boolean>((resolve) => { |
| 19 | this.debounceTimeout = setTimeout(() => { |
| 20 | // When the timeout completes, check if this is still the most recent request |
| 21 | const shouldDebounce = this.currentRequestId !== requestId; |
| 22 | |
| 23 | // If this is the most recent request, it shouldn't be debounced |
| 24 | if (!shouldDebounce) { |
| 25 | this.currentRequestId = undefined; |
| 26 | } |
| 27 | |
| 28 | resolve(shouldDebounce); |
| 29 | }, debounceDelay); |
| 30 | }); |
| 31 | } |
| 32 | } |