节流是什么:节流类似于技能冷却,在触发一个事件后这个事件会开启计时器,在计时器内无法响应更多的触发
防抖是什么:防抖类似于回城打断,再触发一个事件后,再次触发会重新进行计时
应用场景:
节流:经常应用于用户频繁点击的按钮
防抖:页面修改大小时,要重新定位,可以使用防抖,在拖动停止后再重新定位
节流代码:
const f = () =>{
console.log("节流")
}
function throttle(f,time){
let timer = null
return(...args)=>{
if(timer){return}
f.call(undefined,...args)
timer = setTimeout(()=>{timer = null},time)
}
}
const a = throttle(f,3000)
在看上述代码时我最开始无法理解let timer = null 这句话
每次使用函数都重新设置timer为null,这样不就没有意义了吗?
于是我想起了初学时老师讲过var和let有区别,让我们都用let
var可以重复定义一个变量,而let不可以
防抖代码:
const f = () =>{
console.log("防抖")
}
function debounce(f,time){
let timer = null
return(...args)=>{
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
f.call(undefined,...args)
timer = null
},time)
}
}
const a = debounce(f,3000)
熟悉setTimeout和clearTimerout()就可以了
setTimerout(
()=>{}
)
clearTimeout(timer)