How to accurately master the use of function anti-shake and function throttling?

Preamble

Function debouncing (Debouncing) and function throttling (Throttling) are both technologies used to control the execution frequency of functions. They are usually very useful when processing high-frequency triggered events (such as window scrolling, mouse movement, input box input, etc.)

1. Core concepts

Function anti-shake

The core idea of function anti-shake is that when an event continues to trigger, the corresponding function will only be executed after the event stops triggering for a period of time. This means that if an event continues to fire for a certain period of time, the function will not be executed until the event stops firing and waits for a certain delay time.

Key concepts:

  • When an event is triggered, set a timer and execute the function after a certain delay.
  • If the event is triggered again, clear the previous timer and reset the new timer.
  • The timer will only execute the function after a certain amount of time has elapsed since the event has stopped firing.

Function throttling

The core idea of function throttling is to control the execution frequency of a function when an event continues to trigger, ensuring that the function can only be executed once at most within a certain time interval. Different from function stabilization, function throttling will continue to execute functions at a certain time interval without waiting for events to stop triggering.

Key concepts:

  • When an event is triggered, set a timer and only allow the function to be executed once within the timer interval.
  • If the event is triggered again, even if the timer is still counting, the function will not be executed until the timer expires.

2. Code implementation of function anti-shake and throttling

Implementation of function anti-shake:

The key to function anti-shake is to use setTimeout to delay the execution of the function. If the event is triggered again during the delay period, the previous delay is canceled and the new delay is reset.

function debounce(func, delay) {<!-- -->
  let timeoutId;
  return function (...args) {<!-- -->
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {<!-- -->
      func.apply(this, args);
    }, delay);
  };
}

//Usage example
const debouncedFunction = debounce(() => {<!-- -->
  console.log("Debounced function executed.");
}, 1000);

// Call debouncedFunction when an event is triggered
debouncedFunction();

Implementation of function throttling:

The key to function throttling is to use a flag variable to control whether the function can be executed, and to set a timer to reset the flag variable within the timer so that the function can be executed within the next time interval.

function throttle(func, delay) {<!-- -->
  let canRun = true;
  return function (...args) {<!-- -->
    if (!canRun) return;
    canRun = false;
    setTimeout(() => {<!-- -->
      func.apply(this, args);
      canRun = true;
    }, delay);
  };
}

//Usage example
const throttledFunction = throttle(() => {<!-- -->
  console.log("Throttled function executed.");
}, 1000);

// Call throttledFunction when an event is triggered
throttledFunction();

3. Optimization of function anti-shake and throttling

The implementation of function debouncing (Debouncing) and function throttling (Throttling) can be further optimized to meet different needs and performance requirements. Here are some possible optimizations:

Optimization of function anti-shake:

Immediate execution: Sometimes, you may want to execute a function immediately when the event is triggered, and then perform a debounce delay. This can be achieved by setting a parameter.

function debounce(func, delay, immediate) {<!-- -->
  let timeoutId;
  return function (...args) {<!-- -->
    const context = this;
    const later = () => {<!-- -->
      timeoutId = null;
      if (!immediate) func.apply(context, args);
    };
    clearTimeout(timeoutId);
    if (immediate & amp; & amp; !timeoutId) func.apply(context, args);
    timeoutId = setTimeout(later, delay);
  };
}

Cancel anti-shake: Sometimes, you may want to be able to cancel anti-shake, that is, execute the function immediately and cancel the delay. This can be achieved by returning a cancellation function

function debounce(func, delay) {<!-- -->
  let timeoutId;
  function debounced(...args) {<!-- -->
    const context = this;
    const later = () => {<!-- -->
      timeoutId = null;
      func.apply(context, args);
    };
    clearTimeout(timeoutId);
    timeoutId = setTimeout(later, delay);
  }
  debounced.cancel = function () {<!-- -->
    clearTimeout(timeoutId);
  };
  return debounced;
}

Optimization of function throttling:

Execute immediately at start: Similar to function debounce, you can add a parameter to execute the function once immediately at the beginning of the interval.

function throttle(func, delay, immediate) {<!-- -->
  let canRun = true;
  return function (...args) {<!-- -->
    const context = this;
    if (immediate & amp; & amp; canRun) {<!-- -->
      func.apply(context, args);
      canRun = false;
    }
    if (!immediate) {<!-- -->
      if (canRun) {<!-- -->
        canRun = false;
        setTimeout(() => {<!-- -->
          func.apply(context, args);
          canRun = true;
        }, delay);
      }
    }
  };
}

Return the result of the last execution: Sometimes, you may need to return the result of the last execution while throttling the function.

function throttle(func, delay) {<!-- -->
  let canRun = true;
  let lastResult;
  return function (...args) {<!-- -->
    const context = this;
    if (canRun) {<!-- -->
      lastResult = func.apply(context, args);
      canRun = false;
      setTimeout(() => {<!-- -->
        canRun = true;
      }, delay);
    }
    return lastResult;
  };
}

4. Comparison of function anti-shake and throttling

Function debouncing (Debouncing) and function throttling (Throttling) are both technologies used to control the execution frequency of functions, but they have different uses and characteristics in practical applications. Here’s how they compare:

1. Purpose and use:

The main purpose of function anti-shake is to ensure that when an event is triggered continuously, the corresponding function is only executed after the event stops triggering for a period of time. It is suitable for scenarios that require waiting for the user to stop the operation before executing it, such as real-time search of the input box, window resizing, etc.

The main purpose of function throttling is to control the execution frequency of the function to ensure that the function can only be executed once at most once within a certain time interval. It is suitable for scenarios where the frequency of function execution needs to be limited, such as scrolling events, button click anti-shake, etc.

2. Execution time:

When an event is triggered continuously, function anti-shake will only execute the function once after the event stops triggering for a period of time.

Function throttling will continue to execute functions at a certain time interval, regardless of whether events are triggered continuously.

3. Response speed:

Function debounce may have a delay after the event stops, as it waits for a period of time to ensure the event stops.

Function throttling executes the function every time interval, so the response is faster, but is still limited by the time interval.

4. Implementation method:

Function debouncing usually uses setTimeout to delay the execution of the function and cancel the previous delay every time an event is triggered.

Function throttling limits the execution of a function by controlling a flag variable, and the timer is used to reset the flag variable.

5. Application scenarios of function anti-shake and throttling

Function debouncing (Debouncing) and function throttling (Throttling) are very useful technologies when dealing with high-frequency triggered events. They can improve user experience, improve performance, and reduce unnecessary function execution. The following are common scenarios in their practical applications:

Application scenarios of function anti-shake:

  • Input box real-time search: When a user enters content in the search box, anti-shake can ensure that the search request is only triggered after the user stops typing for a period of time to reduce the load on the server.

  • Window resizing: During window resizing, anti-shaking ensures that the relayout is only performed after the user stops dragging the window borders.

  • Button click anti-shake: Anti-shake can be used for button click events to prevent users from clicking the button multiple times and ensure that only one click event handler is executed.

  • Delayed execution: When you need to delay the execution of a function, anti-shake can be used to ensure that the function is only executed once within a certain period of time, such as delayed execution of animations or prompt messages.

  • Scroll event: In scroll event processing, anti-shake can be used to ensure that the event processing function is only executed after the user stops scrolling the page for a period of time, reducing the number of executions of the function.

Application scenarios of function throttling:

  • Scroll events: Scroll events may be triggered frequently. Using throttling can limit the execution frequency of event processing functions and improve performance.

  • Drag and drop operation: During the drag and drop operation, using throttling can ensure that the drag event handler is only executed within a certain time interval to smooth the drag and drop operation.

  • Page scrolling loading: In infinite scrolling pages, using throttling can control the trigger frequency of loading more content and avoid loading large amounts of data in an instant.

  • Mouse move events: When processing mouse move events, using throttling can reduce the number of executions of the event processing function and improve performance.

  • Timer update: When a certain status or interface element needs to be updated regularly, using throttling can ensure that the update operation is only performed within a certain time interval to avoid frequent refreshes.