完全適用的防抖
/**
* @param {Function} func
* @param {number} wait
* @param {boolean} immediate
* @return {*}
*/
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function() {
// 據(jù)上一次觸發(fā)時間間隔
const last = +new Date() - timestamp
// 上次被包裝函數(shù)被調(diào)用時間間隔 last 小于設(shè)定時間間隔 wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// 如果設(shè)定為immediate===true癣防,因?yàn)殚_始邊界已經(jīng)調(diào)用過了此處無需調(diào)用
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}
return function(...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
// 如果延時不存在,重新設(shè)定延時
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}
return result
}
}