Anti – shake and throttling background

To deal with frequent event firing due to frequent operations, an optimization is made to trigger event callbacks when input is complete, rather than firing event callbacks whenever data changes.

Image stabilization

The principle of anti-shake

How it works (compare the following example) : The event callback function (doSomething) is executed after a period of time (300 ms). If it is called again within this period of time, the time starts from 0 to 300 ms. If the function is not called again within a predetermined period of time, the event callback function (doSomething) is executed.

What it feels like: Because the time has to be recalculated from 0, it occurs to use the clear timer clearTimeout(timeout);

To understand:

// Example 1:
// _.debounce(event callback function, interval time, [true immediately /false]) uses the underscore library
The onmousemove function will be called as long as the mouse moves, that is, _. Debounce (doSomething, 300); Debounce then always recalculates the time, and if the move is more than 300 milliseconds apart, the doSomething callback is executed
container.onmousemove = _.debounce(doSomething, 300);
Copy the code

Handwritten image stabilization

function myDebounce(fn, interval = 500) {
  let timeout = null;
  return function () {
    clearTimeout(timeout);
    timeout = setTimeout(() = > {
      fn.apply(this.arguments);
    }, interval);
  };
}
function doSomething(){
    // Onmousemove triggers the event callback function
}
container.onmousemove = myDebounce(doSomething, 300);
Copy the code

The throttle

Throttling principle

Principle: Trigger continuously in unit time, but will only execute once. For example, if the event repeatedly triggers the click event within 300 seconds, it will only execute once. When the timing starts in the next 300 seconds, it will execute again in the next 300 seconds. That is, 600s fires events continuously but only executes them twice. (Principle tells us that we need a flag bit)

Feeling: Since it can only be executed once in a period of time, it occurred to me to use the flag variable

Handwritten throttling

function myThrottle(fn, interval = 500) {
  let run = true;
  return function () {
    if(! run)return;
    run = false;
    setTimeout(() = > {
      fn.apply(this.arguments);
      run = true;
    }, interval);
  };
}

function doSomething(){
    // Onmousemove triggers the event callback function
}
container.onmousemove = myThrottle(doSomething, 300);
Copy the code