美文网首页
函数闭包应用节流和防抖

函数闭包应用节流和防抖

作者: Chris__Liu | 来源:发表于2019-01-17 10:13 被阅读0次

    应用场景主要是用户频繁操作后,通过定时请求。可以减少服务器的请求次数。

    防抖debounce

    function debounce(fn,delay){
        let timer = null;
        return function(){
            let context = this
            let args = arguments
            clearTimeout(timer)
            timer = setTimeout(function(){
                fn.apply(context,args) 
            },delay)
        }
    }
    let flag = 0
    function foo(){
        flag++
        console.log('Number of calls:%d',flag)
    }
    
    document.addEventListener('click',debounce(foo,1000))
    

    节流 throttle

    相对于防抖更加宽松,防抖主要是用户触发最后一次事件后,延迟一段事件触发,而节流会规定的时间内触发一次事件。

    function throttle(fn,delay){
        let timer = null;
        let startTime = Date.now()
    
        return function(){
            let curTime = Date .now()
            let remaining = delay - (curTime -startTime)
            const context = this
            const args = arguments
    
            clearTimeout(timer)
            if(remaining<=0){
                fn.apply(context,args)
                startTime = Date.now();
            }else{
                timer = setTimeout(fn,remaining)
            }
        }
    }
    function xxx(){
        console.log('1')
    }
    document.addEventListener('click', throttle(xxx,5000))
    

    相关文章

      网友评论

          本文标题:函数闭包应用节流和防抖

          本文链接:https://www.haomeiwen.com/subject/yjmbdqtx.html