@consumidor-positivo/ts-utils - v1.13.0
    Preparing search index...

    Function throttle

    • Creates a throttled function that only invokes the provided function at most once per specified interval.

      The throttled function comes with a cancel method to cancel delayed invocations.

      This utility is useful for limiting the rate at which a function can fire, such as during window resize or scroll events, API calls, or other intensive operations.

      Type Parameters

      • T extends (...args: any[]) => any

        The function type

      Parameters

      • func: T

        The function to throttle

      • wait: number

        The number of milliseconds to throttle invocations to

      Returns T & { cancel: () => void }

      A throttled function with a cancel method

      import { throttle } from '@consumidor-positivo/ts-utils';

      // Basic usage - limit a function to run at most once every 500ms
      const throttledScroll = throttle(() => {
      console.log('Scroll event handled');
      }, 500);

      window.addEventListener('scroll', throttledScroll);

      // With arguments and return value
      const throttledCalculate = throttle((a: number, b: number) => {
      console.log('Calculating...');
      return a + b;
      }, 300);

      // Cancel any pending invocation
      setTimeout(() => {
      throttledCalculate.cancel();
      console.log('Throttled function canceled');
      }, 1000);