/*
防抖
*/
function debounce(fn, delay) {
let timer
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
// 测试
function a() {
console.log('run')
}
const debounceA = debounce(a, 1000)
window.addEventListener('scroll', debounceA )
/*
节流
*/
function throttle(fn, delay) {
let last = 0 // 上次触发时间
return function (...args) {
const now = Date.now()
if (now - last > delay) {
last = now
fn.apply(this, args)
}
}
}
// 测试
function a() {
console.log('run')
}
const throttleA = throttle(a, 1000)
window.addEventListener('scroll', throttleA)
防抖、节流
最新推荐文章于 2022-10-28 10:58:03 发布