1.调用代码多次,只执行最后一次
//函数防抖
const debounce = (fn, duration = 1000) => {
let timer
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn(...args)
}, duration)
}
}
const fn = () => {
console.log('关门')
}
const newFn = debounce(fn, 3000)
newFn()
newFn()
newFn()
2.监听页面滚动
const handler = debounce(() => {
console.log('滚动了')
})
window.addEventListener("scroll", handler)