原理
防抖:当短期内有大量的事件触发时,只会执行最后一次触发的事件。
节流:当短期内有大量的事件解发时,只会执行第一次触发的事件。
实现
防抖
const debounce = (fn) => {
let timeout = null
return () => {
clearTimeout(timeout)
timeout = setTimeout(() => fn.apply(this, arguments), 300)
}
}
节流
const throttle = (fn) => {
let timeout = null
return () => {
if (timeout) return
timeout = setTimeout(() => {
fn.apply(this, arguments)
timeout = null
}, 300)
}
}
网友评论