A stabilization.

The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculatedCopy the code
  • Cancel the previous delayed call method each time an event is raised
function debounce(fn) {
      lettimeout = null; // Create a flag to store the return value of the timerreturn function() { clearTimeout(timeout); // Every time the user enters, the previous one is addedsetTimeout clear Clear Timeout =setTimeout(() => {// Then create a new onesetFn function fn.apply(this, arguments); }, 500); }; }function sayHi() {
      console.log('Anti-shake succeeded');
    }

    var inp = document.getElementById('inp');
    inp.addEventListener('input', debounce(sayHi)); / / image stabilizationCopy the code

2. The throttle

High frequency events fire, but only execute once in n seconds, so throttling dilutes the frequency of the function's executionCopy the code
  • Each time an event is triggered, it determines whether there is a delay function waiting to be executed
function throttle(fn) {
      let canRun = true; // Save a tag through a closurereturn function () {
        if(! canRun)return; // Check whether the tag is at the beginning of the functiontrue, not fortruethereturn
        canRun = false; // Set to immediatelyfalse
        setTimeout(() => {// Place the execution of the function passed in externallysetThe Timeout of fn. Apply (this, the arguments); / / in at lastsetAfter Timeout completes, set the flag totrue(Key) indicates that the next loop is ready to execute. The flag is always when the timer is not executedfalse, at the beginning byreturnOff canRun =true;
        }, 500);
      };
    }
    function sayHi(e) {
      console.log(e.target.innerWidth, e.target.innerHeight);
    }
    window.addEventListener('resize', throttle(sayHi));
Copy the code