防抖与节流

2020-09-14  本文已影响0人  天神9527

防抖

当持续触发事件时,一定时间段内没有再次触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又触发了一次,就重新开始计时

//防抖
function debounce(fn, delay) {
    var timerId = null;
    return function() {
        timerId && clearTimeout(timerId) && (timerId = null);
        timerId = setTimeout(fn, delay);
    }
}

//处理函数
function handle() {
    console.log(Math.random());
}

//滚动事件
window.addEventListener('scroll', debounce(handle, 1000));

界面滚动时,控制台没有打印内容,当停止滚动1s,控制台打印随机数

节流

当持续触发事件时,保证一定时间段内只调用一次事件处理函数

给出两种实现方式

// 1.定时器

let throttle = function(func, delay) {
    let timer = null;
    return function() {
        let args = arguments;
        if(!timer) {
            timer = setTimeout(() => {
                func.apply(this, args);
                clearTimeout(timer);
                timer = null;
            }, delay);
        }
    }
}

function handle() {
    console.log(Math.random());
}

window.addEventListener('scroll', throttle(handle, 1000));

利用定时器实现方式,和用setTimout实现setInterval的原理一样。与防抖的差别在于clearTimeout的调用和timerId的赋值处理。

// 2.时间戳
function throttle  (func, delay) {
    let prev = Date.now();
    return function() {
        let context = this;
        let args = arguments;
        let now = Date.now();
        if (now - prev >= delay) {
            func.apply(context, args);
            prev = Date.now();
        }
    }
}

function handle() {
    console.log(Math.random());
}

window.addEventListener('scroll', throttle(handle, 1000));
上一篇 下一篇

猜你喜欢

热点阅读