节流-定时器版--- n秒后第一次执行,停止触发后会再执行一次事件(前提是第一次执行后还在点击)

文章链接

单位:2秒

0

      function throttle(fn, delay) {
        let timer = null
        return function () {
          if (!timer) {
            timer = setTimeout(() => {
              timer = null
              fn.apply(this, arguments)
            }, delay)
          }
        }
      }

      let count = 0
      function addCount() {
        counterDom.textContent = ++count
      }
      const counterDom = document.getElementById('counter')
      const btnDom = document.getElementById('btn')
      const throttled = throttle(addCount, 2000)
      btnDom.addEventListener('click', throttled)
    
综合版-有取消功能