JS 实现原生防抖函数时遇到的onclick和行内onclick的区别问题

在html的onclick行内添加一个方法,每次触发点击事件都会执行该方法
看似没什么问题,但如果这个方法返回的是一个方法呢,如果我们想让返回出来的方法得到执行,就要在行内的末尾加上一对 ()
结果就是每次执行返回出来的内部方法都是新的,闭包?我们想要使用的闭包莫得了。

解决方案 2种:

  • 在script标签中给dom元素的onclick赋值这个方法的执行,返回出来的内部方法就可以应用闭包
  • 使用addEventListener给dom元素添加click事件,赋值依然为外层方法的执行
<body>
  <button id="btn">按钮</button>
  <script>
    const btn = document.getElementById('btn');
    // btn.addEventListener('click', debounce(real, 500))
    btn.onclick = debounce(real, 500);
    // 这是一个防抖函数
    function debounce(func, delay) {
      
      
      var timer = null;
      return function () {
      
      
        var firsttime = !timer;
        if (firsttime) {
      
      
          func.call(this, ...arguments);
        }
        if (timer) {
      
      
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
      
      
          timer = null;
          if (!firsttime) {
      
      
            func.call(this, ...arguments);
          }
        }, delay)
      }
    }
    function real() {
      
      
      console.log(123);
    }
  </script>
</body>

猜你喜欢

转载自blog.csdn.net/weixin_45543674/article/details/121578034