1-函数去抖

78 阅读1分钟

平时直接引入lodash用了,最近有人问到,那就再写一下吧!!!

手写版本

    <body>
        test
        <script src="./test-debounce.js"></script>
        <script src="./test-throttle.js"></script>
    </body>

test-debounce.js

/**
 * @description 函数去抖
 * @param func 函数
 * @param wait 延迟毫秒
 * @param immediate 立即执行(在wait时间间隔内再次触发不会执行func)
 */

function debounce(func, wait, immediate = false) {
    let timeout;
    // 匿名函数 可以绑定this,
    // 箭头函数 绑定this不会生效
    return function () {
        if (timeout) clearTimeout(timeout);

        if (immediate) {
            const callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait);

            if (callNow) func.apply(this, arguments);
        } else {
            timeout = setTimeout(func.bind(this, ...arguments), wait);
        }
    };
}

function countNumber(...reset) {
    console.log('this.name :', this.name);
}

var name = 'myname window';

const obj = {
    name: 'myname obj',
    countNumber,
};

// obj.countNumber();

const debounced = debounce(obj.countNumber, 3000, false);

window.addEventListener('resize', debounced.bind(obj, 1, 2, 3, 4));

// test.js:18 (5) [1, 2, 3, 4, Event]
// test.js:19 this : {name: "myname obj", countNumber: ƒ}
// test.js:20 this.name : myname obj

lodash 版本

// console.log('_ :', _);

// func (Function): 要防抖动的函数。
// [wait=0] (number): 需要延迟的毫秒数。
// [options={}] (Object): 选项对象。
// [options.leading=false] (boolean): 指定在延迟开始前调用。
// [options.maxWait] (number): 设置 func 允许被延迟的最大值。
// [options.trailing=true] (boolean): 指定在延迟结束后调用。

const debounced = _.debounce(
    () => {
        console.log('111 :', 111);
    },
    1000,
    {
        maxWait: 3000,
        leading: false,
        trailing: true,
    }
);
console.log('debounced :', debounced);
window.addEventListener('resize', debounced);