js anti-shake and throttling [handwritten code]

Anti-shake and throttling are commonly used optimization methods in front-end development to control the execution frequency of functions.

anti shake

​ Debouncing is a programming technique that is mainly used to prevent an event from being triggered frequently. Only the last time the event is triggered will be executed within a period of time. Anti-shake is a common user experience optimization technique that can make web pages smoother during user interaction.

​ For example, in an input box, anti-shake can prevent frequent requests caused by frequent input, and each request is only issued uniformly after the last input.

​Usually use the setTimeout() function to achieve anti-shake. When events are triggered frequently, clear the last unexecuted scheduled task after each triggered event, and then reschedule a new scheduled task, so as to ensure that the last trigger of the event will be implement.

Handwriting anti-shake

//一个被防抖的函数 func
//一个默认等待时间 wait(默认为 500ms)
function debounce(func,wait=500){
    
      //默认等待时间
    let timeout
    let debounced = function(){
    
    
      //如果有定时任务,准备从新开始计时
      if (timeout) clearTimeout(timeout);
      //如果没有定时任务,则从现在开始安排定时任务
      timeout = setTimeout(() => {
    
    
        func.apply(this, arguments);
      }, wait);
    }
    //注意最后返回的是一个被防抖过的函数
    return debounced
}

Anti-shake example

Examples of anti-shake:

Suppose we have a search box, when the user is typing, we want to not trigger the request for a period of time after the user's input is completed, to avoid too many requests. We can achieve this with anti-shake.

For example:

const searchBox = document.querySelector("#search");

//防抖函数
function debounce(func, wait) {
    
    
    let timeout;
    return function() {
    
    
        clearTimeout(timeout);
        timeout = setTimeout(() => {
    
    
            func.apply(this, arguments);
        }, wait);
    };
}

//请求函数
function requestData() {
    
    
    console.log("请求数据");
}

searchBox.addEventListener("input", debounce(requestData, 500));

In this way, when the user enters a search keyword, the data is only requested if the user does not enter it again within 500 milliseconds after the user completes the input.

throttling

​ Throttling, that is, limiting the number of executions of a function within a certain period of time, redundant calls will be ignored, and only executed once within the specified time. This technology is widely used in event processing scenarios that need to be triggered frequently, such as user interaction response and animation.

For example: in the process of the user dragging the window, we don't need to re-render the interface with each operation of the user, but only once after the operation is completed; or when the user enters the search content, we don't need to re-render the interface with each operation The input of a character requests the background, but after the user input is completed, wait for a period of time before requesting the background.

There are many implementation methods, the common ones are timestamp version and timer version. The timestamp version records the time when the function was last called, and judges whether the difference between the current time and the last call time is greater than the specified time interval each time it is called. The timer version records the timed task set when the function is called, and judges whether the timed task exists each time it is called. If it exists, it does not trigger the function. If it does not exist, it triggers the function and sets the timed task.

 //实现1:时间戳
 // 第一次会触发,最后一次不会触发 [内心更加认可]【推荐】
  function throttle1(func, wait) {
    
    
    let old = 0; //上一次触发的时间
    return function () {
    
    
      let now = +new Date();  //+new Date()日期对象隐式转换为时间戳整数
      if (now - old > wait) {
    
    
        old = now;
        func.apply(this, arguments);
      }
    }
  }

//实现2:
// 第一次不会触发,最后一次会触发
  function throttle2(func, wait) {
    
    
    let timeout;
    return function () {
    
    
      if (!timeout) {
    
    
        timeout = setTimeout(() => {
    
    
          func.apply(this, arguments);
          timeout = null;
        }, wait)
      }
    }
  }

Anti-shake and throttling are two different technologies, both of which are designed to solve the problem of calling functions too frequently. The differences are as follows:

1. Anti-shake (Debouncing): In a certain period of time, if there are many events triggered, the function is only executed once after the end of this period of time.

2. Throttling: In a certain period of time, the function is only executed once, even if there are multiple events triggered, it will only be executed once in this period of time.

To sum up, anti-shake is to wait for the triggering of events within a certain period of time. If there are multiple events triggered during this period of time, the function will only be executed once after the end of this period of time; and throttling is during a certain period of time. The function is only executed once, even if there are multiple events triggered, the function will only be executed once within this period of time

Guess you like

Origin blog.csdn.net/m0_61696809/article/details/129353691