Front-end page optimization (1) Performance: anti-shake and throttling

The debounce and throttling functions in the front end are to solve the performance problem when events are triggered frequently.

1. Anti-shake

The function of the anti-shake function is to wait for a period of time after the event is triggered and then execute the corresponding processing logic. If the same event is triggered again within this period, the timing will be restarted. This can avoid frequent execution of processing logic when events are triggered continuously, thus achieving a throttling effect.

A common anti-shake function is implemented as follows:

function debounce(func, delay) {
  let timer;
  
  return function() {
    const context = this;
    const args = arguments;
    
    clearTimeout(timer);
    timer = setTimeout(function() {
      func.apply(context, args);
    }, delay);
  };
}

Among them, funcrepresents the processing logic that needs to be executed and delayrepresents the delay time.

2. Throttling

The function of the throttling function is to execute the corresponding processing logic at most once within a certain period of time. If an event is triggered frequently within this time period, only the first time the processing logic will be executed, and subsequent triggers will be ignored.

A common throttling function is implemented as follows:

function throttle(func, interval) {
  let lastTime = 0;
  
  return function() {
    const context = this;
    const args = arguments;
    const currentTime = Date.now();
    
    if (currentTime - lastTime > interval) {
      func.apply(context, args);
      lastTime = currentTime;
    }
  };
}

Among them, funcrepresents the processing logic that needs to be executed and intervalrepresents the time interval.

Using anti-shake and throttling functions can effectively control the execution frequency of functions and improve web page performance and user experience. For example, when listening to scroll events, you can use the throttling function to limit the frequency of event triggers to avoid excessive calculation and update operations; in the input box search function, you can use the anti-shake function to reduce the number of requests and reduce server pressure.

Guess you like

Origin blog.csdn.net/weixin_62635213/article/details/132334678