js性能优化之---防抖函数

使用场景
  • input的时时触发搜索功能
  • scroll事件的滚动条位置的监测
  • resize事件监听窗口变化等
举个栗子(input框时时触发搜索功能)

普通未防抖款

var textElement = document.getElementById('test');
var timer;
textElement.oninput = function(){
    console.log('造吧,木有防抖效果');
}

1141519-20190315142215789-1120395127.png

普通防抖款

var textElement = document.getElementById('test');
var timer;
textElement.oninput = function(){
    console.log('oninput事件');
    if(timer){
        clearTimeout(timer);
    }
    timer = setTimeout(function(){
        timer = null;
        console.log('添加防抖效果之后的操作')
    },2000)
}

1141519-20190315142230699-2096637060.png

封装防抖款

function antishake(fn,delay){
    return function(){
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn();
        },delay);
    }
}

function business(){
    console.log('添加防抖效果之后的操作')
}

textElement.oninput = function(){
    console.log('oninput事件')
    antishake(business,800)();
}

1141519-20190315142247224-1134178346.png

转载于:https://www.cnblogs.com/Ivy-s/p/10536821.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值