This is the 16th day of my participation in Gwen Challenge


Hi, I’m Daotin, front end team leader. If you want to get more front end highlights, follow me and unlock new front end growth poses.

The following text:

Front-end work will inevitably use anti – shake and throttling, but before always confused the definition of anti – shake and throttling, so today to sort out the difference between anti – shake and throttling, and how to use, when should use anti – shake, when should use throttling.

Problem description

What is front end anti – shake and throttling? What’s the difference? How does it work?

Image stabilization

Concept: The function will be executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time will be recalculated.

Each time an event is triggered, clear the timer and set a new timer.

Application Scenarios:

  • Input box search lenovo, the user constantly input values trigger input events, with anti – shake to save request resources.
  • Windows triggers resize. Resize the browser window repeatedly to trigger resize. Use stabilization to make it trigger only once

Basic VUE usage:

onDebounce() {
    // Timer is defined globally for this object, and the same timer is called each time onDebounce is executed
    clearTimeout(this.timer); 
    this.timer = setTimeout(() = >{
        this.getAjax(); // The background requests Ajax information
    }, 2000);
},
Copy the code

Basic JS code:

function debounce(fn) {
  let timeout = null; // Create a closure that holds a token to store the return value of the timer
  return function () {
    clearTimeout(timeout); // Remove the previous setTimeout whenever the user enters
    timeout = setTimeout(() = > { // Then create a new setTimeout to ensure that the fn function is not executed if there are any more characters in the interval after the input character
      fn.call(this);
    }, 500);
  };
}

document.getElementById('inp').addEventListener('input', debounce(getAjax)); / / image stabilization
Copy the code

The throttle

Concept: High frequency events fire, but only execute once in n seconds, so throttling dilutes the execution frequency of the function.

Each trigger event determines whether the timer is full. If it is, the timer will be reset. Otherwise, nothing will be done.

Specific idea 1: set a trigger flag flag=true, in the event to determine: if flag==true, a scheduled task, and set flag=false, in the scheduled task to execute the code to obtain Ajax, and set flag=true; If flag=false, return and do nothing until the timer is full.

Specific idea 2: Do not use the timer, directly compare the timestamp difference.

Application Scenarios:

  • Click /mousedown(only triggered once per unit of time)
  • Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle

Vue code:

onThrottle() {
    if(!this.throttleFlag) return;
        
    this.throttleFlag = false;
    this.timer = setTimeout(() = >{
        this.getAjax();
        this.throttleFlag = true;
    }, 2000);
}
Copy the code

Thread 1-js code:

function throttle(fn) {
  let canRun = true; // Save a tag through a closure
  return function () {
    if(! canRun)return; // Check whether the flag is true at the beginning of the function, otherwise return
    canRun = false; // Set it to false immediately
    setTimeout(() = > { // Place the execution of an external function in setTimeout
      fn.apply(this.arguments);
      // Finally, set the flag to true after setTimeout (critical) to indicate that the next loop can be executed. The flag is always false when the timer is not executed and is returned at the beginning
      canRun = true;
    }, 500);
  };
}

window.addEventListener('resize', throttle(getAjax));
Copy the code

Vue code:

onThrottle() {
    let now = Date.now();
    if (now - this.lastTime > 5000) { // 5s
        this.getAjax();
        this.lastTime = now; / / update time}}Copy the code

Idea 2-js code:

 function throttle (fn) {
    let lastTime = 0;  // The time of the last trigger
    return function () {
        let now = Date.now();
        if (now - lastTime > 5000) {
           fn.call(this);
           lastTime = now; / / update time}}}Copy the code

Reference links

[1] 7 minutes to understand JS throttling, anti-shake and usage scenarios: _juejin.cn/post/684490… [2] the Daily – Interview – Question: github.com/Advanced-Fr…


Recent hot articles:

  • Waterfall flow, it’s so easy
  • Four common ajax cross-domain solutions (easy to understand)
  • Vue. Js Naming Style Guide (Easy to remember Version)

Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin