JS function throttling and function anti chattering

preface:

During window resize, scroll, input box content verification and other operations, if the frequency of event handler function calls is unlimited, it will increase the burden on the browser and lead to very poor user experience.

At this time, we can use debounce and throttle to reduce the call frequency without affecting the actual effect.  

Function anti shake

Function debounce: when an event is triggered continuously and no event is triggered again within a certain period of time, the event handling function will execute once. If the event is triggered again before the set time, the delay will be restarted.

As shown in the following figure, when the scroll event is triggered continuously, the handle function is not executed. When the scroll event is not triggered within 1000 milliseconds, the scroll event will be triggered later.

 

 

example:

// Anti shake
function debounce(func, wait=0) {    
   if (typeof func !== 'function') {
    throw new TypeError('need a function arguments')
   }
   let timeid = null;
        let result;
 
   return function() {
    let context = this;
    let args = arguments;

    if (timeid) {
      clearTimeout(timeid);
    }
    timeid = setTimeout(function() {
      result = func.apply(context, args);
    }, wait);
 
    return result;
   }
}
// Processing function
function handle() {    
    console.log(Math.random()); 
}
// Scroll event
window.addEventListener('scroll', debounce(handle, 1000));
            

When the scroll event is triggered continuously, the event handler handle will be called only once after stopping scrolling for 1000 milliseconds, that is, the event handler handle has not been executed during the continuous triggering of the scroll event.

Function throttling

Function throttling: when an event is triggered continuously, it is ensured that the event handling function is called only once within a certain period of time.

The popular explanation of throttling is that as soon as we open the faucet, the water flows down. Adhering to the fine traditional virtue of diligence and thrift, we should turn down the faucet, preferably drop by drop at a certain time interval according to a certain law.

As shown in the following figure, when the scroll event is triggered continuously, the handle function is not executed immediately, and the handle function is executed every 1000 milliseconds.

 

example:

throttle code (timestamp):

let throttle = function(func, delay) {            
  let prev = Date.now();            
  return function() {                
    let context = this;                
    let args = arguments;                
    let now = Date.now();                
    if (now - prev >= delay) {                    
      func.apply(context, args);                    
      prev = Date.now();                
    }            
  }        
}        
function handle() {            
  console.log(Math.random());        
}        
window.addEventListener('scroll', throttle(handle, 1000));

throttle code (timer):

// throttle throttle Code (timer):
let throttle = function(func, delay) {            
    let timer = null;            
    return function() {                
        let context = this;               
        let args = arguments;                
        if (!timer) {                    
            timer = setTimeout(function() {                        
                func.apply(context, args);                        
                timer = null;                    
            }, delay);                
        }            
    }        
}        
function handle() {            
    console.log(Math.random());        
}        
window.addEventListener('scroll', throttle(handle, 1000));

 

summary

Function anti shake: combine several operations into one operation. The principle is to maintain a timer. It is specified that the function will be triggered after the delay time, but if it is triggered again within the delay time, the previous timer will be cancelled and reset. In this way, only the last operation can be triggered.

Function throttling: the function is triggered only once in a certain time. The principle is to trigger the function by judging whether it reaches a certain time.

difference:   Function throttling ensures that the real event processing function will be executed once within the specified time no matter how frequently the event is triggered, and function anti chattering only triggers the function once after the last event.

For example, in the scenario of unlimited page loading, we need users to send Ajax requests at regular intervals when scrolling the page, rather than requesting data when users stop scrolling the page. This scenario is suitable for throttling technology.

 

PS: anti shake and throttling can effectively reduce the loss of browser engine and prevent page blocking and jamming. You should master them skillfully. Finally, thanks again for the original author's summary and enthusiastic sharing technology to make our life better

 

  Reference link: https://www.cnblogs.com/momo798/p/9177767.html

 

Tags: Front-end

Posted on Wed, 01 Dec 2021 10:15:00 -0500 by flash_78