节流 :在单位时间内,只触发一次。eg.scroll


function throttle(fn,delay=500){
let flag = true
return function(...args){
let context = this
if(!flag) return
flag = false
setTimeout(()=>{
fn.apply(context,args)
flag = true
},delay)
}
}


防抖:事件触发n秒后再执行回调,n秒内触发,重新计时。eg.resize|change


function debounce(fn,delay=500){
let timer = null
return function(...args){
let context = this
timer && clearTimeout(timer)
timer = setTimeout(()=>{
fn.apply(context,args)
},delay)
}
}