节流函数
function throttle(fn, time) {
let previous = 0
return function() {
const now = Date.now()
const that = this
const args = arguments
if (now - previous > time) {
fn.apply(that, args)
previous = now
}
}
}
防抖函数
function debounce(fn, time = 1000, immediate = true) {
let timer
return function() {
const that = this
const args = arguments
if (timer) {
return clearTimeout(timer)
}
if (immediate) {
const callNow = !timer
timer = setTimeout(() => {
timer = null
}, time)
if (callNow) {
fn.apply(that, args)
}
} else {
timer = setTimeout(() => {
fn.apply(that, args)
}, time)
}
}
}