debounce.js 1.14 KB
/**
 * 防抖工具函数
 *
 * @description 创建防抖函数,延迟执行 func
 * @param {Function} func - 需要防抖的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {Function} 防抖后的函数
 *
 * @example
 * const debouncedSearch = debounce(() => {
 *   console.log('搜索')
 * }, 500)
 *
 * debouncedSearch() // 等待 500ms 后执行
 * debouncedSearch() // 取消上一次,重新计时
 */
export function debounce(func, delay = 500) {
  let timer = null

  return function (...args) {
    // 清除之前的定时器
    if (timer) {
      clearTimeout(timer)
    }

    // 设置新的定时器
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

/**
 * 防抖 Hook
 *
 * @description 创建响应式防抖函数
 * @param {Function} func - 需要防抖的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {Function} 防抖后的函数
 *
 * @example
 * import { debounceFn } from '@/utils/debounce'
 *
 * const debouncedSearch = debounceFn(async () => {
 *   await fetchData()
 * }, 500)
 */
export function debounceFn(func, delay = 500) {
  return debounce(func, delay)
}