All files / frontend/src/utils debounce.ts

100% Statements 11/11
100% Branches 4/4
100% Functions 3/3
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                      1x 7x               7x 10x 2x   10x           7x 5x 3x 3x       7x    
/**
 * Creates a debounce function that delays execution until after a specified delay.
 *
 * @param delay - The number of milliseconds to delay
 * @returns An object with `debounce` and `cancel` methods
 *
 * @example
 * ```typescript
 * const filterDebounce = createDebounce(200);
 *
 * // Debounce a function call
 * filterDebounce.debounce(() => {
 *   console.log('This will execute after 200ms');
 * });
 *
 * // Cancel pending execution
 * filterDebounce.cancel();
 * ```
 */
export const createDebounce = (delay: number) => {
  let timeoutId: NodeJS.Timeout | null = null;
 
  /**
   * Debounces a function call. If called multiple times rapidly,
   * only the last call will execute after the delay period.
   *
   * @param fn - The function to debounce
   */
  const debounce = (fn: () => void): void => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(fn, delay);
  };
 
  /**
   * Cancels any pending debounced execution.
   */
  const cancel = (): void => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  };
 
  return { debounce, cancel };
};