Image stabilization (debounce)

The role of anti – shake: to frequently triggered action last execution. The common behavior is search engine search input (Baidu is triggered every time, no use of anti – shake), only after the user completed the search for matching.

Implementation idea: set up a delay timer, each trigger, cancel the previous timer and reset, to achieve the last execution of the effect.

function debounce(fn,delay=500,immediate){
  let timer = null,immediateTimer = null;
  
  return function(){
      let args = arguments, context = this;
      
      // The first time
      if(immediate && ! immediateTimer){ fn.apply(context,args);// Reset the first trigger flag, otherwise the next cycle will be disturbed
          immediateTimer = setTimeout(() = >{
          	immediateTimer = null;
          },delay);
      }
      // If there are multiple executions, the reset action should be executed in the timer;
      if(immediateTimer) clearTimeout(immediateTimer);
      if(timer) clearTimeout(timer);
      
      timer = setTimeout(() = >{
      	fn.apply(context,args);
          timer = null;
          immediateTimer = null; },delay); }}Copy the code

Use:

let temp = debounce((e) = > {
    console.log(this, e.target.value);
}, 500.true);
input.addEventListener('input', temp);
Copy the code

The throttle (throttle)

The function of throttling: to execute frequently triggered actions according to a certain period. The common behaviors are scrolling event Scroll, moving event mousemove, etc.

Implementation idea: set up a delay timer, each trigger, reset the timer, to achieve the last execution of the effect.

function throttle(fn, delay = 500, immediate = false) {
    let timer = null,
        immediateTimer = null, immediateRunning = ! immediate;return function() {
        let context = this, args = arguments;

        if(immediate && ! immediateRunning) { fn.apply(context, args); immediateRunning =true;
          // // Resets the first execution identifier
          immediateTimer = setTimeout(() = >{
            immediateRunning = false;
          },delay);
          return;
        }

        if(! timer){// If there are subsequent triggers, cancel the immediateTimer in the timer
          if(immediateTimer) {
              clearTimeout(immediateTimer);
              immediateTimer = null;
          };
          
          timer = setTimeout(() = > {
            fn.apply(context, args);
            timer = null;
            immediateTimer = setTimeout(() = >{
              immediateRunning = false;
            },delay);
          }, delay)
        }
    }
  }
Copy the code

Use:

let temp = throttle((e) = > {
    console.log(this, e.target.value);
}, 500.true);
input.addEventListener('input', temp);
Copy the code