【源码】防抖和节流源码分析

前言

防抖、节流主要用于频繁事件触发,例如鼠标移动、改变窗口大小等。lodash等函数库具备相对应的api_.debounce_.throttle

核心技术:闭包。

区别:

  • 防抖, 连续触发, 第一次和最后一次触发有效
  • 节流, 一段时间内仅触发一次(第一次)

本文以防抖函数为例, 详细说明。

实现

原理, 计时器存储状态。

function debounce(fn, delay) {
    return function() {
        console.log(fn.timer, count2);
        let _this = this;
        let _args = arguments;
        fn.timer !== undefined && clearTimeout(fn.timer);
        fn.timer = setTimeout(function() {
            fn.apply(_this, _args);
        }, delay);
    }
}
// 替换
debounce(oldFunction, delay)();

改进, 可多处调用

/**
 * 防抖函数
*/
function debounce(fn, delay) {
    let timer;
    return function () {
        let _this = this;
        let _args = arguments;
        console.log(timer, count2)
        timer !== undefined && clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(_this, _args);
        }, delay);
    }
}
var newFucntion = debounce(oldFunction, delay);
// 替换
newFunction();

我的测试连接, 打开控制台查看

参考

灵感-薄荷周刊, 有错误, 仅供参考

参考blog

参考演示

猜你喜欢

转载自www.cnblogs.com/daaasheng/p/9822193.html