节流-时间戳版- 立刻执行,停止触发后没有办法再执行事件

文章链接

单位:2秒

0

      function throttle(fn, delay) {
        let last = 0
        return function () {
          const now = Date.now()
          if (now - last > delay) {
            fn.apply(this, arguments)
            last = now
          }
        }
      }

      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)
    
定时器版