节流和防抖应用场景及实现

节流

定义:不管事件的触发频率有多高,只会在设定的时间间隔内执行一次目标函数。

应用场景:监听浏览器滚动条事件,触发随机改变body背景颜色的函数changeBgc。不使用节流会导致页面一滚动就疯狂触发changeBgc函数,页面会不停闪动。运用节流函数throttle我们设定1秒时间间隔内只能触发一次changeBgc函数。

js:

//change body backgroundColor randomly
var changeBgc = function(){
    let r = Math.floor(Math.random()*255)
    let g = Math.floor(Math.random()*255)
    let b = Math.floor(Math.random()*255)
    document.body.style.backgroundColor = `rgb(${r},${g},${b})`
}

// bind scroll event to listen window scrolling with throttle
window.addEventListener('scroll',throttle(changeBgc,1000))
// window.addEventListener('scroll',throttle2(changeBgc,1000))


// throttle
function throttle (fun,timeInterval) {
    let timer
    // return a funciton
    return function() {
 		// pass arguments 
        let context = this
        let args = arguments
        // if last function has been apply in timeInterval, skip this function 
        if (timer){
            return 
        }else{
            timer = setTimeout(function(){
                fun.apply(context,args)
                // a function has been apply in timeInterval, we can start next call
                timer = null
            },timeInterval)
        }   
    }
}

// throttle2: timestamp
function throttle2 (fun,timeInterval) {
    let pre = 0
    return function (){
    	// current time at which this funciton will be triggered
        let now = + new Date()
        // if time exceed timeInterval after last function has been apply,  we can start next call
        if (now-pre>timeInterval){
            fun()
            pre = now
        }
        
    }
}

防抖

定义: 触发事件后 n 秒后才执行函数,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

应用场景: 点击按钮发送Ajax请求。不使用防抖可能会导致用户连续点击按钮时,一段时间后多个相应陆续到来,形成抖动,这样连续请求会造成资源浪费。运用防抖函数,如果用户在请求还未发送的时间内再次点击发送按钮,只会执行最后面一次发送回调。

html:

<body>
	<button>点我发送Ajax请求</button>
</body>

js:

const btn = document.querySelector('button')
var sendAjax = function(){
    console.log('send request...');
}
// bind click event to send request
btn.addEventListener('click',debounce(sendAjax,2000))

//debounce
function debounce(fun,delay) {
    let timer
    // return a function
    return function (){
        let context = this
        let args = arguments
        // clear last function, execute current new function
        clearTimeout(timer)
        timer = setTimeout(function(){
            fun.apply(context,args)
        },delay)
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值