防抖节流

60 阅读1分钟

为什么使用防抖节流

为了防止重复点击,当在短时间内重复点击同一个按钮时,就会频繁的调用同一个接口,会出现性能下降,资源请求太频繁等问题。

防抖

在触发事件后n秒后才会执行函数
代码实现:

 function debounce(fn, delay = 1000) {
    let timer = null;
    return function(...args) {
        // 如果在定时时间内再次触发时间,则清空定时器,重新计时
        if (timer) {
            clearTimeout(timer);
        }

        // 事件不再触发
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay)
    }
}

节流

在固定时间内,函数只能触发一次,就是说当连续触发事件时,在这n秒中只执行一次函数
代码实现:

function throttle(fn, timer = 1000) {
    // 定义上一次时间戳
    let prev = 0;
    return function(...args) {
        // 定义下一次时间戳
        let now = new Date();
        if (now - prev > timer) {
            // 时间差大于一秒才触发函数(事件回调函数)
            fn.apply(this, args);
            // 更新时间戳
            prev = now;
        }
    }
}

使用

let ipt = document.querySelector('input');
// 调用防抖
ipt.addEventListener('input', debounce(function(e) {
    console.log(e.target.value);
}))
// 调用节流
ipt.addEventListener('input', throttle(function(e) {
    console.log(e.target.value);
}))