You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
833 B
33 lines
833 B
/**
|
|
* 通用防抖 composable
|
|
* 替代各页面中手动 setTimeout/clearTimeout 的防抖模式
|
|
*/
|
|
export function useDebounce() {
|
|
let timer: ReturnType<typeof setTimeout> | null = null
|
|
|
|
/**
|
|
* 返回一个防抖化的函数
|
|
* @param fn 要防抖的函数
|
|
* @param delay 延迟毫秒数(默认 300ms)
|
|
* @returns 防抖后的函数
|
|
*/
|
|
function debounce<T extends (...args: any[]) => void>(fn: T, delay = 300): (...args: Parameters<T>) => void {
|
|
return (...args: Parameters<T>) => {
|
|
if (timer !== null) clearTimeout(timer)
|
|
timer = setTimeout(() => {
|
|
timer = null
|
|
fn(...args)
|
|
}, delay)
|
|
}
|
|
}
|
|
|
|
/** 清除等待中的定时器 */
|
|
function cancel() {
|
|
if (timer !== null) {
|
|
clearTimeout(timer)
|
|
timer = null
|
|
}
|
|
}
|
|
|
|
return { debounce, cancel }
|
|
}
|