1、防抖
function debounce(fn, delay) {
// 声明一个变量timer---定时器
let timer
return function (…args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
// test
function task() {
console.log(‘run task’)
}
const debounceTask = debounce(task, 1000)
window.addEventListener(‘scroll’, debounceTask)
2、节流
function throttle(fn, delay) {
// 最后触发时间
let last = 0 // Last trigger time
return (…args) => {
// 获取当前时间
const now = Date.now()
// 如果当前时间减去最后触发时间大于延迟的时间
if (now-last> delay) {
last = now
fn.apply(this, args)
}
}
}
// test
function task() {
console.log(‘run task’)
}
const throttleTask = throttle(task, 1000)
window.addEventListener(‘scroll’, throttleTask)