JavaScript之节流防抖

146 阅读1分钟

节流函数throttle

函数节流指的是在一定的时间间隔内(例如10秒)只执行一次,在这10秒内无视后来产生的函数调用

throttle实现

function throttle(fn, wait) {
    let previous = 0;
    return function (...args) {
        let now = 1 * new Date();
        if (now - previous > wait) {
            previous = now;
            fn.apply(this, args)
        }
    }
}

function fn(params) {
    console.log(params)
}

const betterFn = throttle(fn, 3000);

setInterval(function () {
    betterFn('abc')
}, 100);

函数防抖指的是无论触发了多少回调,只执行最后一次。

debounce实现

function debounce(fn, wait) {
    // 通过闭包缓存一个定时器id
    let timer = null;
    return function (...args) {
        // 如果已经设定过了定时器就清空上次定时器
        if (timer) {
            clearTimeout(timer);
        }
        
        // 开始设定一个定时器,定时器结束后执行传入的函数
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, wait);
    }
}

function fn(params) {
    console.log(params);
}

var betterFn = debounce(fn, 1000);


document.addEventListener('scroll', function () {
    betterFn(123);
});