Skip to content

Instantly share code, notes, and snippets.

@floatrx
Created June 29, 2024 13:58
Show Gist options
  • Save floatrx/8107738cea9d5fd43d1cbb867ebb6972 to your computer and use it in GitHub Desktop.
Save floatrx/8107738cea9d5fd43d1cbb867ebb6972 to your computer and use it in GitHub Desktop.
Debounce
import { DEFAULT_DEBOUNCE_DELAY } from '@/config/const';
/**
* Debounce function
* @param fn - function to debounce
* @param delay - delay in milliseconds
* @returns debounced function
*/
export const debounce = <T extends AnyFn>(
fn: T,
delay: number = DEFAULT_DEBOUNCE_DELAY,
): ((...args: Parameters<T>) => void) => {
let timeoutId: NodeJS.Timeout;
return (...args: Parameters<T>) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
};
import { useCallback } from 'react';
import { DEFAULT_DEBOUNCE_DELAY } from '@/config/const';
import { debounce } from '@/lib/timing/debounce';
/**
* Debounce function (hook)
* NOTE: fn should be ignored in the deps array
* @param fn - function to debounce
* @param delay - delay in milliseconds
* @returns debounced function
*/
export const useDebounce = <T extends AnyFn>(fn: T, delay: number = DEFAULT_DEBOUNCE_DELAY): T => {
// Use useCallback to return a memoized version of the debounced function
return useCallback(debounce(fn, delay), [delay]) as T; // eslint-disable-line
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment