# 防抖和节流

# 防抖

作用是在短时间内多次触发同一个函数。只执行最后一次,或者只在开始时执行。 应用场景如:scrollresize

// debounce 函数接受一个函数和延迟执行的时间作为参数
function debounce(fn, delay){
    // 维护一个 timer
    let timer = null;
    
    return function() {
        // 获取函数的作用域和变量
        let that = this;
        let args = arguments;
        
        clearTimeout(timer);
        timer = setTimeout(function(){
            fn.apply(that, args);
        }, delay)
    }
}
// 在 debounce 中包装我们的函数,过 1 秒触发一次
window.addEventListener('scroll', debounce(function() {
    console.log('scroll');
}, 1000));

# 节流

和防抖类似,节流是在一段时间内只允许函数执行一次。

应用场景如:输入框的联想,可以限定用户在输入时,只在每两秒钟响应一次联想。

let throttle = function(func, delay){
    let timer = null;

    return function(){
        let that = this;
        let args = arguments;
        if(!timer){
            timer = setTimeout(function(){
                func.apply(that, args);
                timer = null;
            },delay);
        }
    }
}
let input = document.getElementById('input');
input.addEventListener('input', throttle(function() {
    console.log('input')
}, 1000))