防抖:
如果短时间内大量触发同一事件,只会执行一次函数。--滚动
页面resize事件,常见于需要做页面适配的时候。需要根据最终呈现的页面情况进行dom渲染(这种情形一般是使用防抖,因为只需要判断最后一次的变化情况)
function debounce(fn,delay){
let timer=null
let that=this
return function(){
if(timer){
clearTimeout(timer)
}
timer=setTimeout(()=>{
fn.call(that,...arguments)
},delay)
}
}
节流:
如果短时间内大量触发同一事件,那么在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效。
搜索框input事件,例如要支持输入实时搜索可以使用节流方案(间隔一段时间就必须查询相关内容),或者实现输入间隔大于某个值(如500ms),就当做用户输入完成,然后开始搜索,具体使用哪种方案要看业务需求。
function throttle(fn,delay){
let flag=true
let that=this
return function(){
if(!flag){return false}
flag=false
setTimeout(()=>{
flag=true
fn.call(that,...arguments)
},delay)
}
}