Both shaking and throttling are designed to solve performance problems caused by a large number of functions being fired in a short period of time;

Function image stabilization

Function stabilization means that after the event is triggered, the function can only be executed once within the specified time. If the event is triggered again within the specified time, the execution time of the function will be recalculated.Copy the code
function debounce(fn,delay){
  let timeId = null
  return function(){
    if(timeId){clearTimeout(timeId)}
    timeId = setTimeout(() = >{
      fn.apply(this.arguments)
      timeId = null
    },delay) 
  }
}

const debounced = debounce(() = >{console.log('hi')},5000)

debounced()
debounced()
Copy the code

Function of the throttle

Limit a function to executing only once during a specified period of time.Copy the code
function fireball(fn,time){
  let canUse = true
  return function(){
    if(canUse){
      fn.apply(this.arguments)
      canUse = false;
      
      setTimeout(() = >canUse = true,time)
    }else{
      console.log('In skill CD')}}}const fireballs = fireball(() = >console.log('Fireball'),10000)
setInterval(() = >{
   fireballs()
},1000)
Copy the code

To summarize the difference between anti-shaking and throttling:

Effect:

Function stabilization is executed only once in a certain period of time; Function throttling, on the other hand, is performed at intervals, ensuring that the actual event handler is executed within a specified period of time, no matter how frequently the event is fired.

– principle:

Anti – shaking maintains a timer that fires after a delay, but if it fires again during a delay, the current timer will be cleared and the timeout call will be reset. This way, only the last operation can be triggered.

Throttling fires the function by determining whether a certain time has been reached. If not, a timer is used to delay it, and the next event resets the timer.