节流 throttle
表现为:输出、节流、节流、节流
const throttle = (fn, time) => {
let timer = null
return (...args) => {
if(timer) {return}
fn.call(undefined, ...args)
timer = setTimeout(()=>{
timer = null
}, time)
}
}
//使用方法:
const f = throttle(()=>{console.log('hi')}, 3000)
f() // 打印 hi
f() //打印失败
f() //打印失败
防抖 debounce
表现为:抖动、抖动、抖动、输出
const debounce = (fn, time) => {
let timer = null
return (...args)=>{
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.call(undefined, ...args)
timer = null
}, time)
}
}
//使用方法:
const f = debounce(()=>{console.log('hi')}, 3000)
f() //打印失败
f() //打印失败
f() // 打印 hi
二者代码的区别仅在于
节流:
if(timer) {return}
防抖:
if(timer) { clearTimeout(timer) }