SoFunction
Updated on 2025-04-14

Examples of several methods to achieve elegance in front-end anti-shake and throttling

introduction

In web front-end development, we often encounter scenarios where the frequency of function execution needs to be limited. For example, when users quickly click buttons, window resize, scroll pages, or input box text changes, if these events are not processed, it may lead to too many unnecessary calculations or requests, which will affect the user experience and even cause performance problems. To solve these problems, we can use two technologies: Debuncing and Throttling to optimize the response of the code.

The basic concepts and functions of anti-shake and throttling

Anti-shake

Anti-shake refers to the merge of multiple triggered events into one execution. It works for scenarios where we only care about the last trigger, such as the autocomplete feature in the search box, where we only need to send a request to get the result once after the user stops inputting, rather than sending a request every time a character is entered. This reduces the pressure on the server while increasing the response speed of the application.

Throttle

Throttle means that no matter how many events are triggered, the corresponding operation will be performed only once during a period of time. This is very useful in some high-frequency events such as scrolling and window size changes. By limiting the execution frequency of event handling functions, performance degradation caused by excessively frequent operations can be avoided.

Realize anti-shake

Example 1: Basic anti-shake implementation

The following is a simple anti-shake function implementation, which is used to delay the execution of the function until the triggering action is over and wait for the specified time interval before executing:

function debounce(func, wait) {
  let timeout;
  return function(...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => (context, args), wait);
  };
}

// Use exampleconst inputHandler = debounce((event) => {
  ('Input value:', );
}, 300);

('search').addEventListener('input', inputHandler);

Example 2: Anti-shake with Immediate Execution Option

Sometimes we want to execute the function immediately when the event is triggered for the first time, and the subsequent behavior is handled according to normal anti-shake logic. This requirement can be achieved by adding an immediate execution flag:

function debounce(func, wait, immediate) {
  let timeout;
  return function(...args) {
    const context = this;
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      // If it is executed immediately and there is no timer, the function will be called directly      const callNow = !timeout;
      timeout = setTimeout(() => timeout = null, wait);
      if (callNow) (context, args);
    } else {
      timeout = setTimeout(() => (context, args), wait);
    }
  };
}

// Use exampleconst resizeHandler = debounce(function() {
  ('Window resized');
}, 200, true); // Execute it immediately and follow the anti-shake logic in the future
('resize', resizeHandler);

Realize throttling

Example 3: Timestamp version throttling

The throttling of the timestamp version is based on the last execution time and the current time difference to determine whether the function should be executed:

function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    const context = this;
    if (!inThrottle) {
      (context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// Use exampleconst scrollHandler = throttle(() => {
  ('Scrolled');
}, 1000); // Execute at most once per second
('scroll', scrollHandler);

Example 4: Timer version throttling

Another common throttling implementation is to use a timer, which prevents the function from being called repeatedly within the set time interval:

function throttle(func, limit) {
  let lastFunc;
  let lastRan;
  return function() {
    const context = this;
    const args = arguments;
    if (!lastRan) {
      (context, args);
      lastRan = ();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function() {
        if ((() - lastRan) >= limit) {
          (context, args);
          lastRan = ();
        }
      }, limit - (() - lastRan));
    }
  };
}

// Use exampleconst clickHandler = throttle(() => {
  ('Button clicked');
}, 500); // Execute at most once every 500 milliseconds
('myButton').addEventListener('click', clickHandler);

Example 5: Combination of advanced throttling and anti-shake

Sometimes we need to flexibly use throttling and anti-shake according to specific circumstances. For example, for scenarios where more content is loaded without limit, we can start throttling when the user approaches the bottom of the page, and use the anti-shake mechanism to initiate a request to load new data after the user stops scrolling completely:

function loadMoreData() {
  ('Loading more data...');
  // Simulate loading data}

let isFetching = false;

function handleScroll() {
  if (isFetching) return;
  
  const { scrollTop, scrollHeight, clientHeight } = ;
  if (scrollTop + clientHeight >= scrollHeight - 50) {
    isFetching = true;
    // Combined throttling and anti-shake    const throttledAndDebouncedLoad = throttle(debounce(loadMoreData, 300), 1000);
    throttledAndDebouncedLoad();
  }
}

('scroll', handleScroll);

Ideas for using functions from different angles

In addition to the above basic implementation methods, it is also possible to consider expanding anti-shake and throttling in actual projects according to specific needs. For example, you can customize your behavior by configuration items, or in some cases cancel the anti-shake/throttling effect. In addition, it can also be explored in conjunction with frameworks such as React, Vue, or Angular to utilize its lifecycle hooks to manage event handling functions more efficiently.

During the development process, developers should also pay attention to browser compatibility issues to ensure that the features used can work properly in the target environment. In addition, considering the particularity of mobile devices, specialized processing for touch events may also be required to provide a better user experience.

As a web front-end developer, understanding and mastering the concepts of anti-shake and throttling and their multiple implementations can help us make smarter choices when building high-performance, responsive applications. Through in-depth research and practice of these technologies, we can not only improve our personal skills, but also bring greater value to the team.

Summarize

This is the article about the elegant front-end implementation of anti-shake and throttling. For more related front-end implementation of anti-shake and throttling, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!