debouncedFunction()

Debounce a function with a timer and a kill condition. It will run the given function after the timer is finished.

Arguments

Required:

func: Function;
delay: number; // in Milliseconds

Optional:

cancelCondition: (...args: any[]) => boolean;

Returns

(Function): returns the function after the specified delay, if cancel condition wasn't met

Example

const debouncedFuncBase = debouncedFunction({
  func: log('function was called'),
  delay: 2000,
});
// => Calls the function once 2 seconds have elapsed, unless debouncedFuncBase gets called before the delay.

const debouncedFuncWithOptions = debouncedFunction({
  func: log('function was called'),
  delay: 2000,
  cancelCondition: () => numLogs >= 10,
});
// => Calls the function once 2 seconds have elapsed, unless debouncedFuncBase gets called before the delay
      or cancelCondition is met.

Note

In JS libraries such as React, Angular, etc... that currently fully rerender components, if the debouncedFunction() is declared in your component, you should store the component in the given library's callback method.

for example, in React, you would do something like this:

  // Create a debounced version of the input change handler
  // This function will only be recreated if handleInputChange changes during runtime
  const debouncedInputChange = useCallback(
    debouncedFunction({
      func: (value: string) => handleInputChange(value),
      delay: 1000,
    }),
    [handleInputChange]
  );