防抖
/**
*
* @param {function} func - 防抖触发函数
* @param {number} wait - 保护倒计时(毫秒)
* @description 防抖
*/
function debounce(func, wait = 500) {
let timeout
return function () {
const context = this
const args = [...arguments]
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
timeout = null
func.apply(context, args)
}, wait)
}
}
节流
/**
*
* @param {function} func - 节流触发函数
* @param {number} wait - 触发间隔(毫秒)
* @description 节流
*/
export function throttle(func, wait = 200) {
let lastTime
return function (...rest) {
if (!lastTime || new Date().getTime() - lastTime > wait) {
lastTime = +new Date()
func.apply(this, rest)
}
}
}