常用的防抖和节流函数
/**
* 防抖函数
* 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
* 常用于用户的键盘输入搜索、窗口大小调整等。
* @param {Function} func
* @param {second} wait
*/
const debounce = (func, wait) => {
let timer
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
/**
* 节流函数
* 限制函数的执行频率,在规定的时间间隔内,只执行一次函数
* 常用于鼠标的滚动触发记录用户的滚动距离,或者限制频繁点击按钮导致的事件触发
* @param {Function} func
* @param {time second} wait
*/
// 方法一:时间戳
const throttle = (func, wait) => {
let start = 0
return function (...args) {
let now = Date.now()
if (now - start >= wait) {
func.apply(this, args)
start = now
}
}
}
// 方法二:定时器
const throttle1 = (func, wait) => {
let timer = null
return function (...args) {
if (timer) return
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}