ts节流装饰器,ts防抖装饰器

/**
 * @description: 节流装饰器
 * @param {number} delay
 * @return {*}
 */
export const Throttle = (delay: number = 200) => {
  let previous = 0
  return function(target: object, key: string | symbol, descriptor: PropertyDescriptor) {
    const method = descriptor.value
    descriptor.value = function(...args) {
      const now = Date.now()
      if (now - previous > delay) {
        previous = now
        const result = method.call(this, ...args)
        return result
      }
    }
  }
}
/**
 * @description: 防抖装饰器
 * @param {number} delay
 * @return {*}
 */
export const Debounce = (delay: number = 200) => {
  let timer: any = null
  return function(target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
    const method = descriptor.value
    descriptor.value = function(...args) {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        const result = method.call(this, ...args)
        return result
      }, delay)
    }
  }
}

在需要执行防抖的函数上面使用

import { Debounce } from "@/utils/decorator"
// 设置场景缩放
@Debounce()
setScalc() {
   this.g3dView && (this.g3dView.getCanvas().style["transform"] = `scale(${1 / this.$store.state.windowScalc})`)
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容