Skip to content

Instantly share code, notes, and snippets.

@SujitSingh
Created December 21, 2021 21:18
Show Gist options
  • Save SujitSingh/6f3b73517670444619906ea2e46b73d1 to your computer and use it in GitHub Desktop.
Save SujitSingh/6f3b73517670444619906ea2e46b73d1 to your computer and use it in GitHub Desktop.
Debounce in TypeScript

Debounce

function debounceFunction ({
  targetFunction,
  delay = 300,
  immediate = false,
  context,
}: {
  targetFunction: (...args: any[]) => any;
  delay: number;
  immediate?: boolean;
  context?: any;
}): ((...args: any[]) => void) {
  let timeoutId: ReturnType<typeof setTimeout>;

  return (...args: any) => {
    const callContext = context || (this as any),
      callNow = immediate && !timeoutId;

    const laterFunction = () => {
      clearTimeout(timeoutId);
      targetFunction.apply(callContext, args);
    };

    clearTimeout(timeoutId);
    timeoutId = setTimeout(laterFunction, delay);
    if (callNow) laterFunction();
  };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment