节流(Throttling) & 防抖(Debouncing)
- 执行函数
function doSth(sth){
console.log(sth)
}
- 防抖
function debounce(fn,wait){
let timer
return (...args)=>{
timer && clearTimeout(timer)
timer = setTimeout(()=>{
fn.apply(this,args)
timer = null
},wait)
}
}
时间戳版与定时器版区别:时间戳版会立即执行第一次,定时器版会按照delay时间后执行
-
节流时间戳版
function throttle(fn, delay) {
let last
return (...args) => {
let now = +new Date()
if (!last || now >= last + delay) {
last = now
fn.apply(this,args)
}
}
}
- 节流定时器版
function throttle(fn,wait){
let timer
return (...args)=>{
if(!timer){
timer = setTimeout(()=>{
fn.apply(this,args)
timer = null
},wait)
}
}
}
- 节流css版
@keyframes pointer-events { from { pointer-events: none; } to { pointer-events: all; } } .throttle{ animation: pointer-events 3s step-end forwards; &:active{ animation: none; } }
注:无法确定返回函数在何处调用,所以执行fn函数时对其进行绑定this指向

以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号