理解防抖节流

118 阅读1分钟

防抖函数

在函数被触发n秒后执行,在这n秒内再次触发会重置执行时间。

function debounce(fn, delay) {
    let timer;
    return function () {
        let _this = this; 
        let args = arguments;
        if (timer) clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(_this, args); 
        }, delay);
    };
}
//用例
document.onmousemove = debounce(()=>{},1000);

函数防抖的应用场景:

  • 搜索框搜索输入
  • 只需用户最后一次输入完,再发送请求
  • 手机号、邮箱验证输入检测
  • 窗口大小Resize,只需窗口调整完成后,计算窗口大小,防止重复渲染

节流函数

在n秒内多次触发函数只执行一次。

function throttle(fn, delay) {
    let timer;
    return function () {
        let _this = this;
        let args = arguments;
        if (timer) return;
        timer = setTimeout(function () {
            fn.apply(_this, args);
            timer = null;
        }, delay)
    }
}

函数节流的应用场景:

  • 滚动加载,加载更多或滚到底部监听
  • 谷歌搜索框,搜索联想功能
  • 高频点击提交,表单重复提交