ixfx
    Preparing search index...

    Function debounce

    • Returns a debounce function which acts to filter calls to a given function fn.

      Eg, Let's create a debounced wrapped for a function:

      const fn = () => console.log('Hello');
      const debouncedFn = debounce(fn, 1000);

      Now we can call debouncedFn() as often as we like, but it will only execute fn() after 1 second has elapsed since the last invocation. It essentially filters many calls to fewer calls. Each time debounceFn() is called, the timeout is reset, so potentially fn could never be called if the rate of debounceFn being called is faster than the provided timeout.

      Remember that to benefit from debounce, you must call the debounced wrapper, not the original function.

      // Create
      const d = debounce(fn, 1000);

      // Don't do this if we want to benefit from the debounce
      fn();

      // Use the debounced wrapper
      d(); // Only calls fn after 1000s

      A practical use for this is handling high-frequency streams of data, where we don't really care about processing every event, only last event after a period. Debouncing is commonly used on microcontrollers to prevent button presses being counted twice.

      Type Parameters

      Parameters

      • callback: T

        Function to filter access to

      • interval: Interval

        Minimum time between invocations

      • OptionalonResult: (result: Result<ReturnType<T>, any>) => void

        Callback when the result from the wrapped function is available

      Returns (...args: Parameters<T>) => void

      Debounce function

      // Set up debounced handler
      const moveDebounced = debounce((evt) => {
      // Handle event
      }, 500);

      // Wire up event
      el.addEventListener(`pointermove`, moveDebounced);

      Arguments can be passed to the debounced function:

      const fn = (x) => console.log(x);
      const d = debounce(fn, 1000);
      d(10);

      If you want the result of a debounced function when it finally executes, pass in the onResult parameter:

      const isRed = (colour) => colour === `red`;
      const onResult = (result) => {
      if (result.success) {
      console.log(`Value: ${result.value}`);
      }
      }
      const d = debounce(fn, 1000, onResult);

      Note that only the onResult handler for the function call that succeeeds is called, there's no queuing of callbacks.

      If the debounced function throws an error, this will be reported as well:

      if (!result.success) {
      console.error(result.error);
      }