Skip to content

Debounce Directive

源码
ts
app
  .mount('#app')
  .directive('debounce', {
    mounted(el, binding) {
      const [callback, time = 300, arg = [], immediate = false]: [
        Function,
        number,
        any[],
        boolean,
      ] = binding.value
      let timer: any
      // 只执行一次
      let debounceOnly = true

      el.addEventListener('click', () => {
        // 是否立即执行
        if (immediate && debounceOnly) {
          debounceOnly = false
          callback(...arg)
        }

        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          if (!debounceOnly) {
            debounceOnly = true
            return
          }
          callback(...arg)
        }, time)
      })
    },
  })

Released under the MIT License.