手写节流(throttle)、防抖(debounc)。
节流(技能冷却中)
需求:实现一个技能冷却中。我要调用一个技能(闪现),闪现过后在120秒内再次调用闪现,我不会做任何事情,因为它正在冷却中。
//闪现函数
const d = ()=>{
console.log('闪现')
}
//计时器
let timer = null
let 冷却中 = false
function 闪现(){
//判断是否处于冷却中
if(冷却中){return}
d()
//调用d之后用timer来计时,开始冷却
冷却中 = true
timer = setTimeout(()=>{
冷却中 = false
},120*1000)//120秒之后冷却结束
}
但是并没有完成需求 ,因为我有好多技能。
实现任意技能冷却中:
通过一个函数可以生成技能
const createFn = (skill,time) = >{
let timer = null
let 冷却中 = false
return ()=>{
if(冷却中){return}
skill()
冷却中 = true
timer = setTimeout(()=>{
冷却中 = false
},time)//120秒之后冷却结束
}
}
const d = ()=>{
console.log('闪现')
}
//实现闪现函数
const d2 = createFn(d,120*1000)

image.png
如果技能函数需要参数呢?
那就return的时候接收参数,
如果参数很多,那就收集起来变成一个数组,传给skill.
const d = (distance,ff,dd)=>{
console.log('闪现')
}
const args = ['50','70','80']
const createFn = (skill,time) = >{
let timer = null
let 冷却中 = false
return (...args)=>{
if(冷却中){return}
skill(...args)
冷却中 = true
timer = setTimeout(()=>{
冷却中 = false
},time)//120秒之后冷却结束
}
}
标准写法:就回答这个
const throttle = (fn, time) => {
let cd = false
let timer = null
return (...args) => {
if(cd) return
fn.call(undefined, ...args)
cd = true
setTimeout(()=>{
cd = false
}, time)
}
}
const d = ()=>{
console.log('闪现')
}
const d2 = createFn(d,120*1000)
d2()
防抖(回城被打断)
回城需要用三秒,但是再次按回城键会打断回城并重新回城。(再调用重新弄计时)
const f = ()=>{
console.log('回城成功')
}
let timer = null
function x(){
//如果正在记时,也就是回城中再次调用x 那就清除计时,然后再开始计时
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn()
timer = null //回城结束之后
},3000)
}
通用版本
const debounce1 = (fn,time)=>{
let timer = null
return(...args)=>{
if(timer) {clearTimeout(timer)}
timer = setTimeout(()=>{
fn.call(undefined,...args)
timer = null
},time)
}
}
const f = ()=>{
console.log('回城成功')
}
const tp = debounce(f,3000)
tp()
节流经常用在点击按钮上,每五秒只能点一次抢购。
用户频繁点击按钮,我不想让他一直点就给他冷却时间。
防抖用在页面拖拽修改大小时需要重新定位,每次拖动相当于打断,拖动完了去执行重新定位。
用户频繁做拖动 我希望再拖动结束之后再实现一个效果。