All files / debounce debounce.ts

100% Statements 11/11
100% Branches 7/7
100% Functions 4/4
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                                      1x   2x 6x 3x   6x 2x 2x 1x     4x 1x 1x          
/**
 * @description 函数防抖。
 * 1. 传入一个要防抖的函数,和一个延迟毫秒数
 * 2. 延迟时间后,执行回调,如果一定时间内多次触发,则重新计时,只执行最后一次
 * @function debounce
 * @param {Function} func - 要防抖的函数
 * @param {number} [wait=300] - 延迟毫秒数
 * @param {boolean} [immediate=false] - 是否立即执行func
 * @returns {Function} 返回新的(防抖)函数
 * @author liukun <919590347@qq.com>
 * @example
 * import { debounce } from '@wont/utils'
 * const testFn = () => {
 *     console.log('debounce running...')
 * }
 * window.addEventListener('mousemove', debounce(testFn, 500))
 */
 
type Func = (...rest: any[]) => void
export function debounce(func: Function, wait = 300, immediate = false): Func {
  let timer: NodeJS.Timeout | null
  return function next(this: Func, ...rest: any[]) {
    if (timer) {
      clearTimeout(timer)
    }
    if (immediate) {
      !timer && func.apply(this, rest)
      timer = setTimeout(() => {
        timer = null
      }, wait)
    } else {
      timer = setTimeout(() => {
        func.apply(this, rest)
        timer = null
      }, wait)
    }
  }
}