函数节流与防抖

88 阅读1分钟

定义

  • 节流:事件触发后,规定时间内,事件处理函数不能再次被调用。
  • 防抖:多次触发事件,事件处理函数只能执行一次,并且是在触发操作结束时执行。就是说,执行前会等待一段时间。

使用场景

  • 节流:滚动加载更多、搜索框的联想功能、高频点击、表单重复提交。
  • 防抖:搜索框搜索输入,并在输入完自动搜索、手机号邮箱输入检测、窗口大小resize变化后再重新渲染。

代码演示

// 函数节流
function throttle(fn, wait) {
    let self = this;
    const current_time = +new Date();
    if(current_time - last > dur) {
        fn.apply(self, arguments);
        last =+ new Date();
    }
}
​
// 函数防抖
function debounce(fn, wait) {
    let timer;
    let dur = wait || 400;
    return function() {
        clearTimeout(timer);
        let selt = this;
        let args = arguments;
        timer = setTimerout(function() {
            fn.apply(self, args);
        }, dur)
    }
}

\