当前位置:网站首页>Function throttling for performance optimization in JS

Function throttling for performance optimization in JS

2022-06-09 17:58:00 Front end tripod

Definition

   Limit the function execution to one time within the specified time , Ignore the extra triggers .
   It can also be directly understood that throttling means saving flow ( Code execution overhead ), Reduce the original high-frequency operation to the time frequency we set .

Applicable scenario

From the definition, throttling mainly reduces the frequency of function execution , Save the execution cost without delaying the normal function implementation , So most of the scenarios it is applicable to are those with extremely high trigger frequency , If we do not process and there are some expensive operations in the triggered function ( For example, a large number of operations dom Or go ahead ajax Request etc. ) It may block the browser performance and cause a jam . for example :

1、 Browser window change event window.onresize
When the size of the browser window changes onresize Events are triggered very frequently .

2、 mousemove event
When we bind the drag event , This event will also be triggered frequently when dragging .

3、 scroll event
Window scrolling events are also frequently triggered when scrolling .

Realization principle

It can be seen from the above that the cause of the problem is that the function is triggered too frequently , Doing unnecessary operations , So we just need to artificially reduce the trigger frequency to the appropriate frequency . For example, when dragging an event , If you want to initiate a request, it may be enough to send it once or twice a second , Then we can ignore other unnecessary requests according to time .

Code implementation

There are many code implementations for function throttling , The following will be used setTimeout The timer delays execution for a period of time . The specific code is as follows :

/**
 *
 * @param {*} callback  Functions to execute 
 * @param {*} time  Function execution interval 
 *
 */
 
  const saveTraffic = (callback, time) => {
    let timer,
      firstTime;
    
    return function(...res) {
      const _this = this;
 
      //  The first call can be executed directly 
      if (firstTime) {
        callback.apply(_this, res);
        return firstTime = false;
      };
 
      if (timer) return;
 
      timer = setTimeout(() => {
        clearTimeout(timer);
        timer = null;
        callback.apply(_this, res);
      }, time || 500)
    }
  }
 

In the above code, the function to be executed is used as setTimeout The timer is delayed for a period of time , If the delayed execution has not been completed , Then ignore the trigger that calls the function next .

test

  window.onresize = saveTraffic(function(res) {
    console.log(1111, res)
  }, 300);
原网站

版权声明
本文为[Front end tripod]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091747285744.html