防抖函数 debounce debouncePromise
普通函数版
/**
* 函数防抖
* @param fn
* @param ms
* @returns
*/
export const debounce = (fn: Function, ms = 300) => {
let timeoutId: ReturnType<typeof setTimeout>
return function (this: any, ...args: any[]) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
fn.apply(this, args)
}, ms)
}
}
如果用普通的 debounce 去防抖 promise 类型的异步函数,是获取不到返回值的。此时需要使用 Promise 版的防抖函数
Promise 版
/**
* 防抖Promise
* @param fn
* @param delay
* @returns
*/
export function debouncePromise(fn: (...arg0: any[]) => Promise<unknown>, delay = 300) {
let pendingPromise: ReturnType<typeof setTimeout>
return function (...args: any[]) {
if (pendingPromise) {
clearTimeout(pendingPromise)
}
return new Promise((resolve, reject) => {
pendingPromise = setTimeout(() => {
fn(...args)
.then(resolve)
.catch(reject)
}, delay)
})
}
}