Anti shake and throttling

Keywords: Javascript html5

In the actual development, we will encounter such a scenario: we need to register an event, but sometimes this event will be triggered frequently in a short time. The frequent execution of the event will lead to a large number of calculations by the browser and cause the page to jam and fake death. Therefore, we need to solve this problem through some means, So there are two technologies: anti shake and throttling.

Function anti shake and function throttling are both a means to optimize the high-frequency execution of js code.

Anti shake

Function anti shake means that the function will execute once after triggering the high-frequency event in n seconds. If the high-frequency event is triggered again in n seconds, the time will be recalculated; In the whole process, the event function is executed only once. Similar to the buff in the game, if you already have a buff, taking another same buff will re time.

// Function anti shake
let timer = null;
document.getElementById("debounce").onscroll = function() {
  clearTimeout(timer); // Clear the unexecuted code and reset back to the initialization state
  timer = setTimeout(() => {
    console.log("Function anti shake");
  }, 1000);
};

Key points of function anti shake: a timer is also needed to help delay the execution of code. If the method is triggered multiple times before the timing is completed, clear the timer mark recorded last time and start again.

  1. If the method is not triggered after timing, the logic code is executed.

  2. Listen to the rolling event with the debounce element id. first, clear the reference timer of the last unexecuted setTimeout

  3. clearTimeout method that allows invalid values to be passed in. So just execute clearTimeout directly.

  4. Put the code to be executed into the setTimeout timer, and then return the timer reference to the timer cache.

  5. If the countdown ends and no new method triggers the scroll event, execute the code in setTimeout.

  6. The principle of function anti shake is to skillfully use setTimeout as the cache pool, and you can easily clear the code to be executed.

In order to avoid global variable pollution, it is recommended to write closures:

// Do not execute immediately for the first time
function debounce(func, wait) {
    let timer = null;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
            func()
        }, wait);
    }
}
document.getElementById("debounce").onscroll = debounce(() => {
    console.log('Function anti shake');
}, 1000)

Application scenario of function anti shake

  • Search box search input. The user only needs to input it for the last time before sending the request
  • Mobile phone number and email verification input detection
  • Window size Resize. Just calculate the window size after the window adjustment is completed. Prevent duplicate rendering.

throttle

Function throttling: it means that the function will be executed only once in n seconds during the triggering of high-frequency events. For example, the skill CD of the hero in the game cannot be used when the CD is not good.

// Function throttling
let isOk = true;
document.getElementById("throttle").onscroll = function(){
  if(!isOk){ // Judge whether it is idle. If it is in progress, return directly
    return;
  }
  isOk = false;
  setTimeout(function(){
    console.log("Function throttling");
    isOk = true;
  }, 1000);
}

Key points of function throttling: declare a flag bit, set the execution interval, and record whether the current code is executing. If it is idle, the method execution can be triggered normally. Otherwise, cancel the method execution and return directly.

  1. Listen for scroll events with the throttle element id. When isOk is true, it means that the current rolling processing event is idle and can be used. Then the next operation is isOk = false. In this way, other methods that request the execution of scrolling events are return ed.
  2. setTimeout sets the 1000ms time interval, executes the callback function in the timer, releases the flag bit, and allows the execution of the next rolling event.

Here is also how to write closures:

// Function throttling
function throttle(func, wait) {
    let isOk = true;
    return function () {
        if(!isOk){ // Judge whether it is idle. If it is in progress, return directly
            return;
        }
        isOk = false;
        setTimeout(() => {
            func()
            isOk = true;
        }, wait);
    }
}
document.getElementById("throttle").onscroll = debounce(() => {
    console.log('Function throttling');
}, 1000)

[note] the throttling function is not limited to the above implementation scheme,
For example, without the aid of setTimeout, you can replace the status bit with a timestamp, and then use whether the timestamp difference is greater than the specified interval to make a decision. You can also directly use the returned flag of setTimeout as a judgment condition to judge whether the current timer exists. If it exists, it means it is still cooling, and eliminating the timer after executing func means it is activated. The principle is the same.

Application scenario of function throttling

  • Scroll load, load more or scroll to the bottom
  • Baidu search box, search association function
  • Click Submit frequently, and the form will be submitted repeatedly

Posted by JAB Creations on Mon, 18 Oct 2021 17:39:40 -0700