function fn(){
console.log('执行了')
}
//节流
window.addEventListener('scroll',throttle(fn,1000))
function throttle(fn,delay){
let old = 0
let context=null
return function (){
let now = new Date().valueOf()
context=this
if(now-old>delay){
fn.apply(context,arguments)
}
}
}
防抖:到时间执行,没到时间触发重新计时
window.addEventListener('scroll',debounce(fn,1000))
function debounce(fn){
let timer
let context
return function (){
if(timer){
clearTimeout(timer)
}
context = this
timer= setTimeout(()=>{
fn.apply(this,arguments)
},delay)
}
}
function fn(){
console.log('执行了')
}
节流 :在超过设置时间执行function fn(){ console.log('执行了')}//节流window.addEventListener('scroll',throttle(fn,1000))function throttle(fn,delay){ let old = 0 let context=null return function (){ let now = new Date().valueOf() context