函数的防抖与节流(全网最全最细致)

定义

防抖:多次点击,只识别一次。假设我设定500ms内重复点击无数次都只算做一次。
节流:多次点击,只按照规定的的时间间隔来执行。比如,我设定每100ms执行一次,那么在500ms的设定时间内,无论点击多少次,都只识别并且执行5次。

防抖debounce

function debounce(func, wait, immediate) {
    // 多个参数及传递默认的处理
    if (typeof func !== "function") throw new TypeError("func must be an function!");
    if (typeof wait === "undefined") wait = 500;
    if (typeof wait === "boolean") {
        immediate = wait;
        wait = 500;
    }
    if (typeof immediate !== "boolean") immediate = false;
    // 设定定时器返回值标识
    let timer = null;
    return function proxy(...params) {
        let self = this,
            now = immediate && !timer;
        clearTimeout(timer);
        timer = setTimeout(function() {
            timer = null;
            !immediate ? func.call(self, ...params) : null;
        }, wait);

        // 第一次触发就立即执行
        now ? func.call(self, ...params) : null;
    };
}
function handle(ev) {
    // 具体在点击的时候要处理的业务
    console.log('OK', this, ev);
}
submit.onclick = debounce(handle, true);

节流 throttle

在这里插入代码function throttle(func, wait) {
    // 多个参数及传递默认的处理
    if (typeof func !== "function") throw new TypeError("func must be an function!");
    if (typeof wait === "undefined") wait = 500;
    // 设定定时器返回值标识
    let timer = null,
        previous = 0; //设置第一次的操作时间为0
    return function proxy(...params) {
        let self = this,
            now = new Date(),
            remaining = wait - (now - previous)
        if (remaining <= 0) { //如果间隔时间大于wait,就立即执行
            clearTimeout(timer);
            timer = null;
            func.call(self, ...params);
        } else if (!timer) { //如果两次触发的时间小于wait,就设置定时器,继续等待
            timer = setTimeout(function() {
                clearTimeout(timer);
                timer = null;
                previous = new Date();
                func.call(self, ...params);
            }, remaining)
        }
    }
}
function handle() {
    // 具体在点击的时候要处理的业务
    console.log('OK');
}
window.onscroll = throttle(handle)

tips

1.参数要注意判断
2.开始第一次的执行条件要注意,即要不要立即执行函数
3.注意 this的问题 :代码采用了let self=this
4.先记忆,再运用。

参考

珠峰周啸天老师讲解。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值