节流和防抖的个人见解

防抖(debounce),是指在触发事件后n秒内函数只执行一次,如果在n秒内又触发了事件,则会重新计算函数执行时间。

function debounce(func, wait) {
    let timer;

    return function () {
        const context = this;
        const args = arguments;

        if (timer) {
            clearTimeout(timer);
        }
        
        timer = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}

// 只有在触发事件后的n秒内不再次触发事件,才会执行函数
const deFunc = debounce(func, 1000);

节流(throttle),是指连续触发事件,但在n秒内只执行一次函数,稀释函数的执行频率。

// 定时器
function throttle (func, wait) {
    let timer;

    return function () {
        const context = this;
        const args = arguments;

        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                func.apply(context, args);
            }, wait);
        }        
        
    }
}

// 时间戳
function throttle (func, wait) {
    let previous = 0;

    return function () {
        const context = this;
        const args = arguments;
        const current = new Date();
        
        if (current - previous > wait) {
            func.apply(context, args);
            previous = current;
        }
    }
}

// 事件连续触发,但函数每隔n秒执行一次
const thFunc = throttle(func, 1000);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值