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

使用场景

  • input的时时触发搜索功能
  • scroll事件的滚动条位置的监测
  • resize事件监听窗口变化等

举个栗子(input框时时触发搜索功能)

普通未防抖款

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

普通防抖款

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)
}

封装防抖款

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)();
}

原文地址:https://www.cnblogs.com/Ivy-s/p/10536821.html