js 防抖和节流

219 阅读1分钟

节流:用于限流接口的业务场景,连续获取接口时,限制每隔一段时间去获取一次接口,分为时间戳版本和定时器版本。

时间戳版本

function throttle(fn,delay){ 
    let primalTime = 0;        
    return function(){          
        let args = arguments          
        let that = this          
        let nowTime = Date.now()          
        if(nowTime - primalTime >delay){            
            primalTime = nowTime             
            fn.apply(that,args)              
         }           
    }      
 }
function count(){  
      console.log(Math.random())
}
document.getElementById("myinput").onclick = throttle(count, 1000)

定时器版本

function throttle(fn, delay) {
    let timer = null            
    return function () {                
        let args = arguments                
        let that = this                
        if (timer === null) {                    
            timer = setTimeout(function () {                        
            clearTimeout(timer)                        
            fn.apply(that, args)                        
            timer = null                    
            }, delay)                
        }            
    }        
}

防抖:多用于获取输入框实时输入获取接口时,当限制时间之后没输入后就去获取一次接口

function debounce(fn,delay){          
    let timer = null          
    return function(){              
        let args = arguments              
        let that = this              
        if(timer){                 
            clearTimeout(timer)           
        }           
    timer = setTimeout(function(){           
        fn.apply(that,args)           
        timer = null        
        clearTimeout(timer)     
     },delay)   
}}
function count() {    
    console.log(Math.random())
}
document.getElementById("myinput").onclick = debounce(count, 1000)

区别:函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。 比如在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。