js之防抖与节流

定义:多次触发事件后,事件处理函数只执行一次,并且在触发操作结束时执行,一般用于scroll事件
原理:对处理函数进行延时操作,若设定的延时到来之前再次触发事件,则清除上一次的延时操作定时器,重新定时

let timer;
window.onscroll = function(){
  if(timer){
    clearTimeout(timer)
  }
  timer = setTimeout( function(){
   //滚动条位置
   let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
   console.log('滚动条位置:' + scrollTop);
   timer = undefined;
  }, 200)
}

防抖与节流的区别
防抖动是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行
防抖:指定时间内只执行一次,但在等待时间内再次触发事件,重新开始延时。
防抖应用场景 – 搜索功能,实时响应用户输入,给出相关的建议词。

//事件处理函数
function handle(arg){
    //事件处理代码
    console.log('事件处理函数-'+arg);  //事件处理函数-keydownArg
}

//防抖
function debounce(fn, delay){
    let timer = null;
    return function(){
        let content = this;
        let args = arguments;
        if(timer) clearTimeout(timer)
        timer = setTimeout(function(){
            fn.apply(content, args);
        }, delay)
    }
}

//事件绑定
var input = document.getElementById("input"); 
input.onkeydown = debounce(function(){
    handle('keydownArg')
}, 500)

节流:指定时间内只执行一次。
节流应用场景 – 窗口大小改变,下拉加载等。

//事件处理函数
function handle(){
    // 事件处理代码
    console.log('事件处理函数-'+arg); //事件处理函数-resizeArg
}
// 防抖处理
function throttle(fn, delay){
    let timer = null;
    return function(){
        if(timer) return false;
        let content = this;
        let args = arguments;
        timer = setTimeout(function(){
            timer = null
            fn.apply(content, args);
        }, delay)
    }
}

//事件绑定函数
window.onresize = throttle(function(){
    handle('resizeArg')
}, 500)
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值