Function stabilization and function throttling are a means to optimize the JS code with high frequency. Some events in JS, such as browser resize, Scroll, mouse mousemove, mouseover, input input box keypress, will constantly call the callback function bound to the event when triggered. This is a huge waste of resources and reduces front-end performance. To optimize the experience, you need to limit the number of calls to these events.

1. Debounce

The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset.

That is, if the same event is fired many times in a short period of time, the function is executed only once.

function debounce(fn, delay){
     let timerId = null
     return function(){
         const context = this
         if(timerId){window.clearTimeout(timerId)}
         timerId = setTimeout(()=>{
             fn.apply(context, arguments)
             timerId = null
         },delay)
     }
 }
Copy the code

Ii. Throttle

Once in a while, the function is executed.

That is, if a large number of the same events are fired in a short period of time, after a function is executed once, the function is not executed again for a specified period of time. This is equivalent to the cooldown of skills (CD) in the game.

function throttle(fn, delay){
     let canUse = true
     return function(){
         if(canUse){
             fn.apply(this, arguments)
             canUse = false
             setTimeout(()=>canUse = true, delay)
         }
     }
 }
Copy the code

Three, application scenarios

  • Search box input events, to support the search association function can use throttling scheme.

  • The page resize event is usually used when page adaptation is needed. Dom rendering is required based on the final rendering of the page (this is usually done using anti-shake, since only the last change is needed).

Iv. Similarities and differences between the two

Similarities:

  • Both can be implemented using setTimeout.
  • The goal is to reduce the frequency of callback execution to save computing resources.

Difference:

  • Function chattering focuses on events that are fired continuously for a certain period of time and only execute once last, while function throttling focuses on executing only once in a period of time.