节流就是「技能冷却中」
const 闪现 = ()=>{
console.log('闪现');
}
const throttle = (fn, time) =>{
let 冷却中 = false
return (...args)=>{
if(冷却中){
return
}
fn(...args)
冷却中 = true
setTimeout(()=>{
冷却中 = false
}, time)
}
}
// 优化
const throttle2 = (fn, time) =>{
let timer = null
return (...args)=>{
if(timer){
return
}
fn(...args)
timer = setTimeout(()=>{
timer = null
}, time)
}
}
const xx = throttle(闪现, 10 * 1000)
防抖就是「回城被打断」
const debounce = (fn, time) => {
let 回城计时器 = null
return (...args) => {
if (回城计时器 !== null) {
clearTimeout(回城计时器) // 打断回城
}
// 重新回城
回城计时器 = setTimeout(() => {
fn.call(undefined, ...args) // 回城后调用 fn
回城计时器 = null
}, time)
}
}
网友评论