防抖
debounce
只有在某个时间内,没有再次触发某个函数,才真正调用这个函数。
- 多用于 输入搜索,改变窗口大小...
function debounce(fn, wait = 500, immediate = false) {
if (typeof fn !== 'function') {
throw new Error('fn is not a function')
}
let timer = null
return function () {
if (immediate) {
fn.apply(this, arguments)
immediate = flase
}
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, wait)
}
}
节流
throttle
在某个时间段内,无论触发多少次这个事件,执行函数的频率总是固定的。
- 多用于限制 按钮点击...
function throttle(fn, wait = 500, immediate = false) {
if (typeof fn !== 'function') {
throw new Error('fn is not function')
}
let timer = null
return function () {
if (immediate) {
fn.apply(this, arguments)
immediate = flase
}
if (timer !== null) {
return
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, wait)
}
}