SoFunction
Updated on 2025-03-04

TypeScript anti-shake throttling function example detailed explanation

Anti-shake (Debounce):

Anti-shake is used to ensure that a function is triggered only once within a specified time. When it repeatedly triggers the same event in a short period of time, it will write off the previous trigger and will not execute the function until there is no new trigger within the certain time after the initial trigger.

Common utilization scenarios include:

  • Real-time search for input boxes: When the user outputs in the input box, he can use anti-shake technology to perform search and query in advance, reducing unnecessary query and server pressure.
  • Window size resize: When the user resizes the browser window, anti-shake technology can be used to prevent frequent re-calculating layouts during the adjustment process.
  • Form verification: When the user outputs the form, he can use anti-shake technology to perform verification after the user outputs for a period of time, reducing the number of verifications.
/**
  * @description Anti-shake function
  * @param {Function} fn
  * @param {number} delay
  * @param {boolean} immediate
  * @returns {Function}
  */
export function debounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number,
  immediate: boolean = false
): T & { cancel(): void } {
  let timerId: ReturnType<typeof setTimeout> | null = null; // Storage timer  // Define a cancel method to write off anti-shake  const cancel = (): void => {
    if (timerId) {
      clearTimeout(timerId);
      timerId = null;
    }
  };
  const debounced = function (
    this: ThisParameterType<T>,
    ...args: Parameters<T>
  ): void {
    const context = this;
    if (timerId) {
      cancel();
    }
    if (immediate) {
      // If immediate is true and there is no timer to be expected to execute, execute the index function immediately      if (!timerId) {
        (context, args);
      }
      // Set the timer and set timeoutId to null after the delay time      timerId = setTimeout(() => {
        timerId = null;
      }, delay);
    } else {
      // Set the timer and execute the index function after the delay time      timerId = setTimeout(() => {
        (context, args);
      }, delay);
    }
  };
  // Attach the cancel method to the debounced function  (debounced as any).cancel = cancel;
  return debounced as T & { cancel(): void };
}

Throttle:

Throttle is used to ensure that a function is triggered only once at most within a certain time. It executes the function at a fixed distance during the triggering event, regardless of how often the event is triggered.

Common utilization scenarios include:

  • Scroll event listening: For example, when listening to the page scrolls to the bottom and loads more data, you can use throttling technology to reduce the frequency of viewing scrolling status and improve performance.
  • Mouse move event: For example, implement a drag and drop performance, which can reduce the frequency of mouse move event resolution using throttling technology.
  • Animation achievements: When implementing a time-based animation achievement, throttling technology can be used to limit the animation frame rate and increase the calculation overhead.

In short, both anti-shake and throttling technologies can improve performance in different scenarios. Anti-shake is used for situations where repeated triggers only need to be executed once, while throttling is used to limit the frequency of execution of intermittent trigger events.

/**
  * Throttle function
  * @param func Indicator function to throttling
  * @param delay Time distance for throttling (milliseconds)
  * @returns Returns a function solved by throttling
  */
export function throttle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): T {
  let lastCall: number | null = null; // Stamp the last call  return function (
    this: ThisParameterType<T>,
    ...args: Parameters<T>
  ): ReturnType<T> | void {
    const now = (); //Stamp in the future    // If you have not called it before, or the time distance exceeds the set value, execute the index function    if (!lastCall || now - lastCall >= delay) {
      lastCall = now;
      return (this, args);
    }
  } as T;
}

The above is the detailed explanation of the TypeScript anti-shake throttling implementation example. For more information about TypeScript anti-shake throttling, please pay attention to my other related articles!