防抖
触发一个动作多次 只执行最后一次。
function debounce(fn,delay){
let timer; // 存储定时器
let immediate = true; // 内置立即执行,也可以形参配置。
return function(){
let context = this // 存储this
let args = arguments // function自带的arguments 包含event
if(immediate){ // 第一次立即执行
fn.apply(context,args)
immediate = false // 关闭
}
clearTimeout(timer); // 清除定时器
setTimeout(()=>{ // 开启定时器
fn.apply(context,args) // 定时器默认this指向为window 所以这里使用apply。
},delay)
}
}
节流
触发一个动作多次 实际执行次数小于实际操作次数
function throttle(fn,delay){
let timer; // 存储定时器
let immediate = true; // 内置立即执行,也可以形参配置。
return function(){
let context = this // 存储this
let args = arguments // function自带的arguments 包含event
if(immediate){ // 第一次立即执行
fn.apply(context,args)
immediate = false // 关闭
}
if(!timer){ // 如果定时器不存在
timer = setTimeout(()=>{ // 开启定时器
fn.apply(context,args) // 定时器默认this指向为window 所以这里使用apply。
timer = null // 清除
},delay)
}
}
}