The throttle

Throttling refers to events that are triggered at a high frequency, and events that are triggered at a lower frequency, such as zooming a window or scrolling a document, are triggered frequently. We make events not be executed every time, but after a certain interval.

/** * fn: indicates the function to be executed after the trigger. * delay: indicates the delay, number, in s * immediate: Indicates whether to execute the function first. Boolean /function throttle(fn, delay, immediate) {
    let timer = null;
    return function() {
        let args = arguments;
        let that = this;
        
        if(immediate) {
            fn.apply(that, args);
            immediate = false;
        }
        
        if(! timer) { timer =setTimeout(() => {
                fn.apply(that, args);
                timer = null;
            }, delay)
        }
    }
}
Copy the code

Note: Return functions cannot use arrow functions because arrow functions have no arguments

Throttling in addition to timer implementation, you can also consider using time to determine whether the delay time is exceeded

function throttle(fn, delay) {
    let start = Date.now();
    return function() {
        let args = arguments;
        let that = this;
        let now = Date.now();
        if(now - start >= delay) { fn.apply(that, args); start = now; }}}Copy the code

Image stabilization

If the operation is triggered frequently, perform the last operation only. If the user is searching for input information, the input event will be triggered frequently, and the last one will be executed only after the user input has stopped for a certain period of time.

function debounce(fn, delay, immediate) {
    let timer = null;
    
    return function() {
        let args = arguments;
        let that = this;
        
        if(! timer&&immediate) { fn.apply(that, args); }if(timer) {
            clearTimeout(timer);
        }
        
        timer = setTimeout(() => {
            fn.apply(that, args);
        }, delay)
    }
}
Copy the code