directory

  1. Image stabilization
  2. The throttle
  3. Usage scenarios

A, stabilization,

Handwriting - tremble proof/ / image stabilization
function debounce(fn, delay = 300) {
  // The default is 300 milliseconds
  let timer;
  return function () {
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() = > {
      fn.apply(this, args); // Change this to refer to the object referred to by the debounce call
    }, delay);
  };
}

window.addEventListener(
  "scroll",
  debounce(() = > {
    console.log(111);
  }, 1000));Copy the code

1) No parameter version

function debounce1(fn,wait=300){
    let timer;
    return () = >{
        if(timer){clearTimeout(timer)}
        timer = setTimeout(() = >{
            fn();
        }, wait)
    }
};
window.addEventListener(
  "scroll",
  debounce1(() = > {
    console.log(222);
  }, 1000));Copy the code

Second, the throttle

1) Time difference version

// Definition: If an event is continuously triggered, the interval is guaranteed to trigger an event.
//1. Lazy load, scroll load, load more, or monitor the scroll bar position;
//2. Baidu search box, search association function;
//3. Prevent high-frequency click submission, prevent form repeated submission;
function throttle(fn,wait){
    let pre = 0;
    return function(. args){
        let now = Date.now();
        if( now - pre >= wait){
            fn.apply(this,args); pre = now; }}}function handle(){
    console.log(Math.random());
}
window.addEventListener("mousemove",throttle(handle,1000));
Copy the code

2) Flag + Timer version

/ / throttling
// Set a flag
function throttle(fn, delay) {
  let flag = true;
  return () = > {
    if(! flag)return;
    flag = false;
    timer = setTimeout(() = > {
      fn();
      flag = true;
    }, delay);
  };
}

window.addEventListener(
  "scroll",
  throttle(() = > {
    console.log(111);
  }, 1000));Copy the code

Three, use scenarios

1) the throttle

  • Click the mouse repeatedly to trigger the mousedown(trigger only once per unit of time)
  • Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle

2) stabilization

  • Search search association, the user in the continuous input value, use the anti – shake to save the request resources.
  • Windows triggers resize. Resize the browser window repeatedly to trigger resize. Use stabilization to make it trigger only once

Application scenarios of function anti-shake

Sequential events that only need to trigger a callback are:

  • The search box searches for input. The user only needs to type one last time before sending the request
  • Mobile phone number and email verification input detection (triggered by events such as change, input, blur and keyUP, which will be triggered every time you type)
  • Window size Resize. Just after the window adjustment is complete, calculate the window size. Prevent repeated rendering.
  • Mouse mousemove, mouseover
  • In the navigation bar, the user keeps swiping in the navigation area

Application scenarios of function throttling

The scenarios in which a callback is executed at an interval are:

  • Scroll load, load more or scroll to the bottom listen, window.onscroll and slide to the bottom automatically load more
  • Google search box, search association function
  • Click submit frequently, and the form is submitted repeatedly

reference

  • 666 – Anti-shake and throttling

conclusion

  • Both anti-shake and throttling are designed to address the performance cost of frequently triggering an event.
  • Anti-shake is to calm down and execute the last time after frequently triggering an event. For example, when a user stops typing during a search, the method is invoked to save request resources
  • Throttling is to request an event every once in a while when it is triggered frequently. Similar to the long press of a button in a game, the action is triggered regularly once in a while.
  • Anti-shake: execute function n seconds after event trigger, if start again within n seconds, re-time
  • Throttling: When an action is performed multiple times, only one function is executed at a time.