In our daily development process, we may encounter such situations: when we frequently click a button on the page or the mouse wheel keeps rolling, the page will be stuck, which will lead to poor user experience. In order to optimize these problems, we introduce “anti-shake” and “throttling”.

Read this article and you will

  1. Know what is “tremble”, what is “throttle”;
  2. Understand the realization principle of “anti-shake” and “throttling” respectively;
  3. Know the application scenarios of “anti-shake” and “throttling”.

1, the image stabilization

Definition:

Wait n seconds before the event is executed, and if it is triggered within n seconds, the timer restarts.

For example: We take the elevator to and from work every day. Assuming that elevator delivery is a function, assume that the elevator timeout is set to 20 seconds, regardless of the capacity limit.

When the first person enters the elevator, wait for 20 seconds, and the elevator will automatically close and run. If someone enters the elevator again during the waiting process, the elevator will wait for 20 seconds and re-time until the elevator closes and run after 20 seconds, which is anti-shake.

Implementation principle:

Each time an event is emitted, a deferred call method is set and the previous deferred call method is cancelled.

Disadvantages:

If the event is fired repeatedly within a specified time interval, the calling method is delayed continuously.

// The buffeting function
function debounce(fn, delay) {
    let timeout = null;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(() = > {
            fn.apply(this.arguments); }, delay); }}// handle the function
function handle() {
    console.log("防抖");
}
// For example, page scroll events
window.addEventListener("scroll", debonce(handle, 500));
Copy the code

2, throttle

Definition:

It only runs once within n seconds. If it is triggered repeatedly within n seconds, it takes effect only once.

For example: or take the elevator, the elevator door every 20 seconds automatically closed operation, 20 seconds no matter how many people you come in, as long as 20 seconds of time, the door automatically closed.

Implementation principle:

Return each time an event is emitted, if there is a delay function waiting to be executed

// throttling function
function throttle(fn, delay) {
    let flag = true;
    return function() {
        if(! flag)return;
        flag = false;
        setTimeout(() = > {
            fn.apply(this.arguments);
            flag = true;
        }, 500)}}// handle the function
function handle() {
    console.log("The throttle");
}
window.addEventListener("resize", debonce(handle, 500));
Copy the code

Conclusion:

Anti-shake: Combine multiple operations into one operation. The idea is to maintain a timer that fires after the delay, but if it fires again within the delay, the previous timer is cancelled and reset, so that only the last action can be fired.

Application Scenarios:

  • The search box searches for input and only requires the user to enter it one last time before sending the request.
  • Window size resize, just after the window adjustment is complete, calculate the window size. Prevent repeated rendering.

Throttling: causes functions to fire only once in a given period of time.

Application Scenarios:

  • Scroll to load, load more or roll bottom to listen.
  • Search box, search association function.

The difference between:

Similarities:

  • Both can be implemented using setTimeout
  • The purpose is to reduce the frequency of callback execution and save computing resources.

Difference:

Throttling ensures that a true event handler is executed within a specified period of time, no matter how frequently the event is triggered, whereas anti-shake only fires once after the last event.