Anti-shake throttling hooks, pass in a normal function and return a function with anti-shake or throttling

Call the hooksFn method, pass in a normal function, and return a method with anti-shake or throttling

This method receives 3 parameters and returns a new function
param: fnordinary function that needs anti-shake throttling
param: timeanti-shake throttling time
param: typeanti-shake or throttling when the function needs to be returned (notShake: anti-shake throttle: throttling)

type Type = 'notShake' | 'throttle'


/**
 * @params fn 要处理的方法; time 时间;  type  返回的方法类型(notShake:防抖 throttle:节流);
 * @return 返回一个防抖的函数 或者 节流的函数
*/
const hooksFn = (fn: Function, time:number, type: Type) => {
    
    
  let timer:any = null

  if (type === 'throttle') {
    
    
    return function(...args: Array<any>) {
    
    
      if (!timer) {
    
    
        timer = setTimeout(() => {
    
    
          clearTimeout(timer)
          timer = null
        }, time);
        fn(...args)
      }
    }
  } else {
    
    
    return function(...args: Array<any>) {
    
    
      clearTimeout(timer)
      timer = null
      timer = setTimeout(() => {
    
    
        clearTimeout(timer)
        timer = null
        fn(...args)
      }, time);
    }
  }
}


export default hooksFn

Guess you like

Origin blog.csdn.net/weixin_44441196/article/details/121511482