In the aspect of performance optimization, it is very important to compare the basic anti-shake throttling. Here I write a summary of the anti – shake throttling implementation.

The difference between anti-shake and throttling

Both methods are to control the frequency of the occurrence of events. In the same scene, different effects can be achieved.

Scenario: The scroll bar that scrolls the page triggers an event. Now assume that the page scrolls for 10 seconds, and we use 1s as the trigger point for both anti-shake and throttling. Anti - shake: after the page is rolled 10s, the delay is 1s to trigger the event, only triggering the '1' event. Throttling: Events are triggered every 1s during a page scroll of 10s, triggering a total of '10' events.Copy the code

Debounce

Purpose: In a period of time, only one trigger (the last trigger) is executed for multiple triggers of an event. 1, delay trigger event, need timer setTimeout. 2. Only one event is triggered, and only one timer is required. Initialize the timer variable timeout once (only once). 4. Invalidate the timer each time an event is executed. 5. Validates the timer for the last event.Copy the code
/* Buffering (1) with the global variable */
let timeout = null;
function debounce(fn, wait) {
  if(timeout ! = =null) {
    clearTimeout(timeout);
  }
  timeout = setTimeout(fn, wait);
}
for (let i = 0; i < 100; i++) {
  debounce(() = > {
    console.log(11);
  }, 2000);
}

/* Buffeting (2) with closure */

function debounce(fn, wait) {
  let timeout = null;
  return function () {
    if(timeout ! = =null) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(fn, wait);
  };
}
let test = debounce(() = > {
  console.log(11);
}, 1000);
for (let i = 0; i < 100; i++) {
  test();
}
Copy the code

Throttle

Throttling Idea Purpose: To trigger an event more than once in a period of time. 1. Control the frequency of events on a regular basis, using timestamps. 2. When the event is triggered for several times, the timestamp of this trigger should be larger than the timestamp of the last trigger. Otherwise, the event will not be triggered. 3, initialize a timeStamp variable timeStamp, timeStamp is the first time to trigger the timeStamp event. 4. Each time the event is triggered, the timeStamp of the current time is obtained, and timeStamp is subtracted from the current timeStamp. 5. If the difference is greater than 500, execute the event and re-assign the timeStamp of this execution event to timeStamp; If the difference is less than 500, exit the function. (500 is the frequency of events)Copy the code
/ * throttling * /
function throttle(fn, wait) {
  let timeStamp = new Date().getTime();
  return function () {
    let time = new Date().getTime();
    if (time - timeStamp > wait) {
      fn();
      timeStamp = time;
      return;
    }
    return;
  };
}
let test = throttle(() = > {
  console.log("test");
}, 1);
for (let i = 0; i < 10000; i++) {
  test();
}
Copy the code