防抖函数
function debounce(fn, delay = 500) {
let timer;
return function () {
if (timer) {
clearTimeout(timer)
}
const args = arguments
timer = setTimeout(() => {
fn.apply(this, args) // 改变this指向为调用debounce所指的对象
}, delay)
}
}
节流函数
function throttle(fn, delay = 200) {
let flag = true
return function () {
if (!flag) return
flag = false
const args = arguments
setTimeout(() => {
fn.apply(this, args)
flag = true
}, delay)
}
}