防抖函数
export const debounce = (fn, delay = 300) => {
let timer = null
return function (...args) {
if (timer) {
clearInterval(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
节流函数
export const throttle = (fn, delay = 300) => {
let timer = null
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, delay)
}
}
}
使用
window.addEventListener('resize', debounce(onResize))
window.removeEventListener('resize', debounce(onResize))
const test = debounce(onResize)
window.addEventListener('resize', function () {
test(11)
})