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();
  };
};
          Created
          December 21, 2021 21:18 
        
      - 
      
- 
        Save SujitSingh/6f3b73517670444619906ea2e46b73d1 to your computer and use it in GitHub Desktop. 
    Debounce in TypeScript
  
        
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment