函数节流(throttle)& 函数防抖(debounce)

前言

最近项目是遇到了用户频繁操作的问题,最后使用了函数的节流来防止用户误操作,特此记录一下函数节流和防抖

节流(throttle)

原理:在一定时间间隔内,只会执行一次方法。相当于把一定时间间隔内的频繁触发的事件,合成一次调用。就像resize这类频繁触发的事件,对于浏览器的性能消耗很大,使用节流函数,以此降低事件触发的频率

实现方式有两种:时间戳 和 setTimeout 

// 时间戳的方式
function throttle1(fn, delay = 500) {
    let lastTime = 0;
    return function (...args) {
        let currentTime = new Date();
        if(currentTime - lastTime > delay || !lastTime) {
            fn.apply(this, args);
            lastTime = currentTime;
        }
    }
}
// setTimeout的方式
function throttle2 (fn, delay = 500) {
    let timer = null;
    return function (...args) {
        if(!timer) {
            timer = setTimeout(() => {
                fn.apply(this, args);
                clearTimeout(timer);
            }, delay)
        }
    }
}

 

防抖(debounce)

原理:任务频繁触发的情况下,只有触发的间隔超过指定间隔的时候,任务才会执行(即仅仅只会执行一次)。意思就是你尽管触发事件,但是我一定在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行。总之,就是要等你触发完事件 n 秒内不再触发事件后,才执行。

function debounce(fn, interval = 500) {
    let timer = null;
    return function () {
        let context = this;
        let args = agruments;
        clearTimeout(timer); // 每次调用debounce函数,会将前一次timeout清空,确保只会执行一次
        timer = setTimeout(() => {
            fn.apply(context, args)
        }, interval)
    }
}

 

 

      

你可能感兴趣的:(函数,JS基础)