Source Code:
/**
* 消抖函數(shù)
* @param {Function} fn 原始函數(shù)
* @param {Number} delay 延遲執(zhí)行時(shí)間
* @param {Number} wait 最小執(zhí)行間隔
*/
const debounce = (fn, delay, wait = 0) => {
let timeID = 0
let waitTimerID = 0
let args
return (...rest) => {
args = rest
clearTimeout(timeID)
timeID = setTimeout(() => {
clearTimeout(waitTimerID)
waitTimerID = 0
fn.apply(null, args)
}, delay)
if (!waitTimerID && wait > 0) {
waitTimerID = setTimeout(() => {
clearTimeout(timeID)
waitTimerID = 0
fn.apply(null, args)
}, wait)
}
}
}
Example:
function func(n) {
console.log(n)
}
let debouncedFunc = debounce(func, 100, 500)
debouncedFunc(100)