How to write throttling and anti-shake function with vue + typescript (vue-class-component)

vue + typescript (vue-class-component used) how to write throttling and anti-shake function


avoid repeating wheels. I have handwritten once before, which is mainly used for class style vue . After dealing with this , you can use this
P.S. Directly in the method. Based on Vue2

/**
 * , time, time
 * 
 * @param time , 
 * @example
 * class Comp extends Vue {
 *
 *    @Throttle(1000)
 *    private fun() {
 *        console.log('run')
 *    }
 * }
 */
export function Throttle(time: number) {
  return function(
    target: Object,
    propertyKey: string | symbol,
    descriptor: TypedPropertyDescriptor<any>
  ): void {
    const rawValue = descriptor.value
    let _lastTime: number | null = null
    let _lastTimeId: number | null = null
    descriptor.value = function(this: any) {
      const args = arguments
      const now = +new Date()
      if (_lastTimeId) {
        clearTimeout(_lastTimeId)
        _lastTimeId = null
      }
      if (!_lastTime || now - _lastTime > time) {
        // 
        _lastTime = now
        rawValue.apply(this, args)
      } else {
        // 
        _lastTimeId = window.setTimeout(() => {
          _lastTime = +new Date()
          rawValue.apply(this, args)
        }, now - _lastTime)
      }
    }
  }
}

/**
 * 
 * , , time, time, 
 * , , time, 
 * @param time , 
 * @param lastExec , 
 * @param processCallback , true, ()false
 * @example
 * class Comp extends Vue {
 *
 *    @Debounce(1000)
 *    private fun() {
 *        console.log('run')
 *    }
 * }
 */
export function Debounce(
  time: number,
  lastExec = true,
  processCallback: ((val: boolean) => void) | string = () => {}
) {
  if (lastExec) {
    // 
    return function(
      target: Object,
      propertyKey: string | symbol,
      descriptor: TypedPropertyDescriptor<any>
    ): void {
      const rawValue = descriptor.value
      let _lastTimeId: number | null = null
      descriptor.value = function(this: any) {
        const args = arguments
        const processCB =
          typeof processCallback === 'string'
            ? ((this[processCallback] ?? Function.prototype) as Function)
            : processCallback
        processCB.call(this, true)
        if (_lastTimeId) {
          clearTimeout(_lastTimeId)
        }
        _lastTimeId = window.setTimeout(() => {
          processCB.call(this, false)
          rawValue.apply(this, args)
        }, time)
      }
    }
  } else {
    // 
    return function(
      target: Object,
      propertyKey: string | symbol,
      descriptor: TypedPropertyDescriptor<any>
    ): void {
      const rawValue = descriptor.value
      let _lastTime: number | null = null
      descriptor.value = function(this: any) {
        const now = +new Date()
        if (!_lastTime || now - _lastTime > time) {
          // 
          _lastTime = now
          rawValue.apply(this, arguments)
        }
      }
    }
  }
}
Menu