1. 节流(throttle)
节流形象的说就是技能冷却中。
代码演示:
const throttle = (fn, time) => {
let 冷却中 = false
return (...args) => {
if(冷却中) return
fn.call(undefined, ...args)
冷却中 = true
setTimeout(()=>{
冷却中 = false
}, time)
}
}
还有一个简洁版,即删掉“冷却中”变量,直接使用timer代替:
const throttle = (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() // 技能冷却中
2. 防抖(debounce)
防抖形象的说就是回城被打断。
代码演示:
const debounce = (fn, time) => {
let 回城计时器 = null
return (...args)=>{
if(回城计时器 !== null) {
clearTimeout(回城计时器) // 打断回城
}
// 重新回城
回城计时器 = setTimeout(()=>{
fn.call(undefined, ...args) // 回城后调用 fn
回城计时器 = null
}, time)
}
}
3. 适用场景
- throttle
- 鼠标不断点击触发,mousedown(单位时间内只触发一次)
- 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断
- debounce
- search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
- window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
4. 总结
- 函数防抖和函数节流都是防止某一时间频繁触发,但是这两兄弟之间的原理却不一样。
- 函数防抖是某一段时间内只执行一次,而函数节流是间隔时间执行。