什么是防抖和节流?有什么区别?如何实现?
防抖:触发高频事件时,事件在n秒内只执行一次,如果在n秒内再次触发,则重新计算时间
实现:
function debounce(func,wait){
let timer = null //定时器
return function(){
//保存当前调用的dom对象
let _this = this
//保存当前事件对象
clearTimeout(timer) //如果在指定时间又触发了,就清楚定时器,不让他执行下面的func
timer = setTimeout(function(){
//用apply改变func的this指向,使是当前调用的dom对象,顺便把事件对象传过去
func.apply(_this,arg)
},wait)
}
}
function say(){
console.log(this,arg)
console.log('防抖')
}
let inp = document.getElementById('inp')
inp.addEventListener('input',debounce(say,1000))
节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
实现
function throttle(func,wait){
let timer = null
return function(){
let _this = this
let args = arguments
if(!timer){
timer = setTimeout(function(){
timer = null
func.apply(_this,args)
},wait)
}
}
}
function say(e){
console.log(e.target.innerWidth,e.target.innerHeight)
}
window.addEventListener('resize',throttle(say,200))
场景使用
防抖:
search搜索联想,用户在不断输入值时,用防抖来节约请求资源
登录、发短信等按钮避免用户点击太快,以致于发送了多次请求,需要防抖
节流:
window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
总结
防抖:防止抖动,单位时间内事件触发会被重置,避免事件被误伤触发多次。
节流:节流:控制流量,单位时间内事件只能触发一次,如果服务器端的限流即 Rate Limit