JavaScript 截流/防抖函数

5,505 阅读1分钟

1、截流

  • 频繁触发,但只在特定的时间内才执行一次代码
// 截流函数:调用户在限时内执行1次,限时内再次调用,判断时间,所以它在每个时间段内执行1次
function throttle(fn, delay) {
    let prev = Date.now();
    return function() {
        const context = this, args = arguments;
        let now = Date.now();
        console.log(now, prev)
        if (now - prev >= delay) {
            fn.call(context, args);
            prev = now;
        }
    }
}

function throttle2(fn, delay) {
    let timer = null;
    return function() {
        const context = this, args = arguments;
        if (!timer) {
            timer = setTimeout(() => {
                fn.call(context, args);
                timer = null;
            }, delay || 0)
        }
    }
}

2、防抖

  • 频繁触发,但只在特定的时间内没有触发执行条件才执行一次代码
// 防抖函数:调用后在一定时间内函数不执行,过了时间限时执行,在限时内再次调用会重新开启定时器
function debounce(fn, delay = 1000) {
    let timer = null;
    return function () {
        const args = arguments;
        const context = this;
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(() => {
            fn.call(context, args)
        }, delay)
    }