函数节流和防抖

119 阅读1分钟

两者都是为了避免在一个连续的行为中触发多次事件响应;

函数节流

函数节流是指连续的事件中,按照一定的时间间隔去执行一次事件响应,常用场景:

  1. 滚动条滚动事件window.scroll;
  2. DOM的拖拽事件mousemove

实现代码:

// 闭包
function throttle(fn, wait) {
    let timer = null;
    return function (e) {
        const context = this;
        const args = arguments;
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                // 传递参数,如事件对象e;修改this指向;
                fn.apply(context, args);
            }, wait);
        }
    };
}

调用方法:

// 滚动条滚动事件1秒执行一次
window.onscroll = throttle((e) => {
    console.log(e);
}, 1000)

函数防抖

函数节流是指连续的事件中,只执行最后一次事件响应,常用场景:

  1. 输入框输入后做ajax查询请求;
  2. 窗口resize事件后重新计算布局;
  3. 快速重复点击同一个按钮;

实现代码:

function debounce(fn, wait) {
    let timer = null;
    return function() {
        const context = this;
        const args = arguments;
        timer && clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(context, args);
        }, wait);
    }
}

调用方法:

// 输入框输入后做`ajax`查询请求
input.onchange = debounce((e) => {
    console.log(e);
}, 1000)