The principle of anti-shake throttling uses setTimeout and closure characteristics to access variables of external functions. The difference lies in that anti-shake optimizes multiple operations into the last execution. For example, user input only needs to verify the result of the last input, while throttling is performed once after a period of time, which is also an optimization to reduce the frequency and multiple operations

Image stabilization

function debounce(fn, delay, immediate) {
    let timer = null // External variables
    return function() {
        let args = arguments
        let context = this
        if(immediate && ! timer) {// Execute immediately
            fn.apply(context, args)
        }
        if (timer) clearTimeout(timer) // Access external variables internally
        timer = setTimeout(() = > {
            fn.apply(context, args)
        }, delay)
    }
}
Copy the code

The throttle

function throttle(fn, delay, immediate) {
    let timer = null // External variables
    let isNow = immediate // External variables
    return function() {
        let context = this
        let args = arguments
        if (isNow) { // Perform internal access to external variables immediately
            fn.apply(context, args)
            isNow = false // Access external variables internally
        }
        if(! timer) {// There is no delay indicating internal access to external variables
            timer = setTimeout(() = > {
                fn.apply(context, args)
                timer = null
            }, delay)
        }
    }
}
Copy the code