防抖
防抖就是在事件被触发的n秒后执行回调函数,如果在这n秒内该事件又被触发就刷新重新计时
常见使用防抖:
- resize/scroll触发统计事件
- 文本输入验证,不用用户频繁请求
- 多次点击合并为一次
防抖的简单实现
function debounce(fn, delay = 50) {
// 判断fn是否为函数
if (typeof fn !== "function") throw new Error("第一个参数必须为函数")
// 缓存一个定时器id
let timer
// 返回函数是每次用户实际调用的防抖函数
// 如果已经设置过定时器就清空上一次的定时器
// 开始一个新的定时器,延迟执行用户传入的方法
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, delay)
}
}
带立即执行的防抖函数
/**
* 防抖函数,返回函数连续调用时,空闲时间必须大于或等于 wait,func 才会执行
*
* @param {function} func 回调函数
* @param {number} wait 表示时间窗口的间隔
* @param {boolean} immediate 设置为ture时,是否立即调用函数
* @return {function} 返回客户调用函数
*/
function debounce(fn, delay = 50, immediate = true) {
// 判断fn是否为函数
if (typeof fn !== "function") throw new Error("第一个参数必须为函数")
let timer, context, args
// 延迟执行函数
const later = () => setTimeout(() => {
timer = null
if (!immediate) {
fn.apply(context, args)
context = args = null
}
}, delay)
return function (...params) {
if (!timer) {
timer = later()
if (immediate) {
fn.apply(this, params)
} else {
context = this
args = params
}
} else {
clearTimeout(timer)
timer = later()
}
}
}