I don’t even believe it. For a long time, I confused the concept of anti-shake and throttling, which is a kind of hindsight.

Image stabilization

In a nutshell: let a function that has been fired more than once “execute” n units of time after the last firing, that is, each firing is retimed. The function will never be executed as long as the user keeps firing it.

implementation

function debounce(fn, delay){
  let timer = null
  return function(. args){
    const ctx = this
    clearTimeout(timer) / / to empty
    timer = setTimeout(() = >{ fn.call(ctx, ... args) }, delay) } }Copy the code

Usage scenarios

  1. Input Checksum/cache for continuous input
  2. Scroll /resize events that are frequently triggered

The throttle

It says that anti-shake will never be performed when triggered repeatedly. Throttling does not prevent the function from being executed, but rather reduces the flow of water like a reservoir gate, i.e. the control function can only be executed once in a period of time (no matter how many times it is triggered).

function throttle(fn, threshhold = 160){
  let tiemr = null
  let start = new Date().getTime()
  return function(. args){
     const curr = new Date().getTime()
     const ctx = this
     if(curr - start >= threshhold){ 
     fn.apply(ctx, args) // Only a subset of methods are executed once in a period of time
     start = curr
   }
  }
}
Copy the code

Usage scenarios

Click events of some submit buttons to avoid repeated submission (if anti-shake is used, it can also prevent repeated submission, but there will be submission delay, which is not friendly to interaction)