节流 throttle
// 节流就是 [技能冷却中]
const throttle = (fn,time)=>{
let CD = false
return (...args)=>{
if(CD) return
fn.call(undefined,...args)
CD = true
setTimeout(()=>{
CD = false
},time)
}
}
/**
* 还有一个版本是在冷却结束时调用 fn
* 简洁版,删掉冷却中变量,直接使用 timer 代替
*/
const throttle2 = (f,time)=>{
let timer = null
return (...args)=>{
if(timer){return}
f.call(undefined,...args)
timer = setTimeout(()=>{
timer= null
},time)
}
}
// 使用方法
const f = throttle(()=>{console.log('hi')},3000)
f() // 打印 hi
f() // 技能冷却中
效果
防抖 debounce
// 防抖就是【回城被打断】
const debounce = (fn,time)=>{
let TP = null
return (...args)=>{
if(TP !== null){
clearTimeout(TP) // 打断回城
}
// 重新回城
TP = setTimeout(()=>{
fn.call(undefined,...args)//回城后调用 fn
},time)
}
}
效果