JS question: How to distinguish between anti-shake and throttling in a project?

A series of articles on front-end function issues, click above to collect↑

Preface

Hello everyone, I am Da Che!

This article is about 2300 + words, and it takes about 6 minutes to read the whole article.

The main content of this article is divided into three parts. The first part is demand analysis, the second part is implementation steps, and the third part is detailed explanation of the problem.

If you just need a problem solved, just read parts one and two.

If you have more time to learn more about the problem, please read to Part 3.

1. Requirements analysis

When a user clicks a button multiple times and frequently, only one request to the backend interface is allowed to avoid repeated useless requests.

There is no way, our customer has the super power of clicking 10 times per second.

Picture

2. Implementation steps

2.1 Choose anti-shake or throttling?

For controlling the frequency of event triggering, we should easily think of anti-shake and throttling in JS.

Anti-shake (Debounce) and throttling (Throttle) are the most commonly used optimization methods in front-end development, and I believe everyone will use them.

But if you talk about the difference between the two definitions and the different application scenarios of the two, some friends will complain: “Damn, aren’t they all the same!”.

Picture

So, how do we choose?

2.2 The difference between the two definitions

Simple definition distinction:

  • Anti-shake means that within a period of time, multiple executions become only the last execution.

  • Throttling means that within a period of time, multiple executions become only the first time execution.

Detailed definition distinction:

  • Anti-shake (debounce) means that when the same event is triggered multiple times within a period of time, only the last triggered event will be executed.

    This means that in a series of trigger events, if a new trigger event occurs within the specified time interval, the previous trigger event will be ignored and only the last trigger event will be executed.

  • Throttling (throttle) refers to executing the event only once when the same event is triggered multiple times within a period of time.

    This means that no matter how many times the triggering event occurs, only the first event will be executed during the specified interval.

Finally, coupled with the incomparably beautiful and moving sketch of “Da Che Original“:

Picture

Just asking you, who else still doesn’t understand the definition of anti-shake and throttling?

Picture

?

2.3 The difference between the two application scenarios

In real projects, flexibly switching between anti-shake or throttling in different scenarios will further reduce unnecessary resource consumption and improve the performance and responsiveness of front-end applications.

Application scenarios of anti-shake (Debounce):

  • Search box input: When users type in the search box, you can use anti-shake to delay triggering the search request. The request will only be sent after the user stops typing for a period of time to avoid frequent request sending.

  • Window resizing: When a window is resized, antishake can be used to optimize how often certain operations are performed, such as recalculating the layout or re-rendering the page.

  • Button click: When the user clicks a button, anti-shake can be used to ensure that the corresponding operation will only be performed after the user stops clicking for a period of time to avoid misoperation or repeated execution.

Application scenarios of throttling (Throttle):

  • Page scrolling: When the user scrolls the page, you can use throttling to limit how often scroll events are fired. For example, only perform certain operations at fixed intervals during scrolling to reduce the number of event handlers.

  • Mouse movement: You can use throttling to control how often mouse movement events are triggered when the user moves the mouse. For example, the processing logic of mouse movement is only executed once within a certain period of time to avoid excessive calculation and rendering operations.

  • Real-time communication: In real-time communication applications, such as chat applications or online collaboration tools, throttling can be used to limit the frequency of sending messages to avoid sending too many requests or data.

2.4 Code examples of both (don’t get entangled if you understand it)

Examples of anti-shake code are as follows:

// Anti-shake: Click to query the city interface
var btn1 = document.querySelector("button");
var timer;

btn1.onclick = function () {
  //Clear the delayer first, and then call the interface
  clearTimeout(timer);
  // Each time the button is clicked, the delayer will be cleared, and then the time will be reset, delaying the execution of the function for one second.
  timer = setTimeout(city, 3000);
};

function city() {
  ajax({
    method: "get",
    url: "https://geoapi.qweather.com/v2/city/lookup",
    data: {
      location: "Qingdao",
      key: "759cb11054344aaba4b8791ec40274dd",
    },
    aysn: true,
    contentType: "",
    success: function (res) {
      var obj = JSON.parse(res);
      console.log(obj, "Request successful data");
    },
  });

An example of throttling code is as follows:

//Throttling: Print coordinates on the console when the mouse moves
// fn(3000, handlePrint)
function fn(delay, behavior) {
  var timer = null;
  return function (val) {
    if (!timer) {
      timer = setTimeout(function () {
        //Call handlePrint function
        behavior(val);
        timer = null;
      }, delay);
    }
  };
}

function handlePrint(val) {
  console.log(val, "I am the mouse coordinates");
}

//Call fn to pass in the function 1000 and handlePrint.
var handle = fn(3000, handlePrint);

document.addEventListener("mousemove", function (e) {
  handle(e.offsetX);
});

Just take a look at the principle and understand it almost. Don’t get too entangled. You will definitely not use it this way in the project, otherwise you will be criticized.

In real projects such as Vue, functions of third-party libraries are often called. For details, see Part Three.

3. Detailed explanation of the problem

3.1 Collection of commonly used anti-shake throttling function libraries

Popular standalone JavaScript libraries:

  • Lodash (https://lodash.com/): Lodash is a powerful JavaScript utility library that provides a rich set of utility functions, including debounce and throttle. You can use the debounce and throttle functions in Lodash to achieve the corresponding functionality.

  • Underscore.js (https://underscorejs.org/): Underscore.js is another popular JavaScript utility library, similar to Lodash, that also provides debounce and throttle functions for you to use.

  • RxJS (https://rxjs.dev/): RxJS is a reactive programming library that provides a rich set of operators and utility functions, including operators for anti-shaking and throttling . You can use the debounceTime and throttleTime operators in RxJS to achieve the corresponding functionality.

  • Async (https://caolan.github.io/async/): Async is a process control library that provides a variety of tool functions for asynchronous operations. It also contains implementations of the debounce and throttle functions for you to use.

  • Trottle-Debounce (https://github.com/niksy/throttle-debounce): Trottle-Debounce is a JavaScript library that provides anti-shake and throttling functions. It can be used in any JavaScript application program, not tied to a specific framework.

Framework-specific JavaScript libraries:

  • VueUse (https://vueuse.org/): VueUse is a library that provides commonly used Vue.js custom functions, including the implementation of anti-shake and throttling functions. In VueUse, you can use the two custom functions useDebounce and useThrottle to implement anti-shake and throttling functions.

import { useDebounce, useThrottle } from '@vueuse/core';

// Anti-shake
// Trigger with a delay of 500 milliseconds after the value changes
const debouncedValue = useDebounce(value, 500);

// Throttle
// Encapsulate the function as a throttling function and trigger it every 300 milliseconds
const throttledFunction = useThrottle(myFunction, 300);

// Use anti-shake and throttling in Vue components
export default {
  setup() {
    const debouncedValue = useDebounce(value, 500);
    const throttledFunction = useThrottle(myFunction, 300);
  },
}
  • React-use (https://github.com/streamich/react-use): React-use is a library that provides a variety of custom React hooks, including useDebounce and useThrottle. You can use these hooks in react-use to implement debouncing and throttling in your React components.

Conclusion

The original intention of establishing this platform:

  • Create a Q&A platform that only contains front-end questions, allowing everyone to efficiently search and handle the same questions.

  • By continuously accumulating questions, we can practice logical thinking together and learn relevant knowledge points by the way.

  • When you encounter problems or issues that resonate with you, discuss them together, settle together, and grow together.

Thank you for following the WeChat public account: “Programmer Dache”, and then join the Q&A group, let us solve and implement all bugs together!

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Vue entry skill treevue3 basics (JS)Vue3 current situation 39489 people are learning the system