javascript的防抖节流方法

js的防抖节流方法,之前写过,现在在做后台数据滚动加载,触底方法需要用到,就再写一遍,记录一下,后续再用也方便找了。

节流——保证一定时间内只调用一次
应用场景:提交表单、高频的监听事件
移动端,触摸移动就会发起请求
将一定时间内的多个事件合并成一个

let box = document.querySelector('.box')
/* box.addEventListener('touchmove',e=>{
    console.log('请求')
}) */

//节流函数
function throttle(event, time){
    let timer = null
    return _=>{
        if(!timer){
            timer = setTimeout(_=>{
                event()
                timer = null
            }, time)
        }
    }
}

box.addEventListener('touchmove',throttle(_=>{console.log('请求')}, 1000))

防抖 —— 在固定的时间内,事件仅允许发生一次
例如:在下面输入时,会立刻发送请求,防抖就是限制在输入结束后2秒再发送请求

//抖动案例
let telInput = document.querySelector('input')
/* telInput.addEventListener('input', e=>{
    console.log('发起请求')
}) */

//防抖函数
function antiShake(fn, wait){
    let timeOut = null;
    console.log('防抖函数')
    return _ => {
        console.log('timer',timeOut)
        if(timeOut) clearTimeout(timeOut)
        timeOut = setTimeout(fn, wait)
    }
}

//上面案例使用防抖函数
telInput.addEventListener('input', antiShake( _=>{console.log('发起请求')} , 2000))

以上两个方法比较常用,借用了闭包的原理,记录一下。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值