cloud-drive-renamer/src/utils/debounce.ts
Zain 19837f1da8 feat(文件选择器): 实现文件选择器核心功能与UI组件
- 新增文件选择器相关组件:文件列表面板、预览面板、搜索框、工具栏等
- 添加虚拟滚动列表组件提升大文件列表性能
- 实现文件类型过滤、全选/取消全选功能
- 新增预览面板显示重命名结果和冲突检测
- 为各平台适配器添加getAllFiles API方法解决虚拟滚动导致文件丢失问题
- 添加debounce工具函数优化搜索性能
- 更新多语言翻译支持新功能
- 重构悬浮按钮移除徽章计数功能
2025-12-26 17:07:25 +08:00

72 行
1.8 KiB
TypeScript

/**
* Debounce utility function
* Delays function execution until after a specified wait time has elapsed
* since the last time it was invoked
*
* @param func - The function to debounce
* @param wait - The number of milliseconds to delay
* @returns Debounced function
*
* @example
* ```typescript
* const debouncedSearch = debounce((query: string) => {
* console.log('Searching:', query);
* }, 300);
*
* debouncedSearch('a');
* debouncedSearch('ab');
* debouncedSearch('abc'); // Only this will execute after 300ms
* ```
*/
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return function debounced(this: any, ...args: Parameters<T>): void {
// Clear previous timeout
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
// Set new timeout
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
}, wait);
};
}
/**
* Throttle utility function
* Ensures function is called at most once per specified time period
*
* @param func - The function to throttle
* @param limit - The number of milliseconds to limit
* @returns Throttled function
*
* @example
* ```typescript
* const throttledScroll = throttle(() => {
* console.log('Scroll event');
* }, 16); // 60fps
* ```
*/
export function throttle<T extends (...args: any[]) => any>(
func: T,
limit: number
): (...args: Parameters<T>) => void {
let inThrottle = false;
return function throttled(this: any, ...args: Parameters<T>): void {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}