1. If you

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 recalculated

Ideas:

Cancels the previous delayed call method each time the event is emitted

function debounce(fn) {
    let timeout = null; // Create a flag to store the return value of the timer
    return function () {
        clearTimeout(timeout); // Whenever the user enters is enough to remove the previous setTimeout clear
        timeout = setTimeout((a)= > {
            // Then create a new setTimeout to ensure that the fn function is not executed if there are any more characters in the interval after the input character
            fn.apply(this.arguments);
        }, 500);
    };
}
function sayHi() {
    console.log('Anti-shake succeeded');
}
// Get input box DOM node
const inp = document.getElementById('inp');
// Listen for inPU input box changes
inp.addEventListener('input', debounce(sayHi)) / / image stabilization
Copy 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 execution

Ideas:

Each time an event is triggered, it is determined whether there is currently a delay function waiting to be executed

function throttle(fn){
    let canRun = true; // Save a tag through a closure
    return function () {
        if(! canRun)return; // Check whether the flag is true at the beginning of the function, otherwise return
        canRun = false; // Set it to false immediately
        // Place the execution of an external function in Timeout
        setTimeout((a)= > {
            fn.apply(this.arguments);
            // Finally, set the flag to true after setTimeout (critical) to indicate that the next loop can be executed. The flag is always false when the timer is not executed and is returned at the beginning.
            canRun = true;
        }, 500);
    };
}
function sayHi(e) {
    console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi))
Copy the code

If you don’t want to write it yourself, fine! There’s another way! Reference lodash = = >

If you | throttling