InterviewMap/CS-Interview-Knowledge-Map

防抖示例函数展开赋值的写法有误

LegendLeo opened this issue · 2 comments

防抖
这个示例的展开赋值...arg写错了地方,写到里面的话,arg取得的值是 event
应该写到外层的参数中,如下

   const debonce = (func, wait = 100, ...args) => {
     let timer = null
     return function () {
       if (timer) clearTimeout(timer)
       timer = setTimeout(() => {
         func.apply(this, args)
       }, wait)
     }
   }

这样才取得到

我的demo如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Debonce</title>
</head>
<body>
  <input type="button" value="1">
  <script>
    let btn = document.querySelector('input')
    function add(step = 1) {
      btn.value = parseInt(btn.value) + step
    }
    const debonce = (func, wait = 100, ...args) => {
      let timer = null
      return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          func.apply(this, args)
        }, wait)
      }
    }
    btn.addEventListener('click', debonce(add, 800, 3))
  </script>
</body>
</html>

@LegendLeo 原来的写法是对的,你想象一下假如不考虑debonce,你直接btn.addEventListener('click', add),这个时候add的接受的参数也是event。你的需求应该是下面的写法:

<script>
    let btn = document.querySelector('input')
    function add(step = 1) {
      btn.value = parseInt(btn.value) + step
    }
    function onClick(e) {
       add(3)
    }
    const debonce = (func, wait = 100) => {
      let timer = null
      return function (...args) {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          func.apply(this, args)
        }, wait)
      }
    }
    btn.addEventListener('click', debonce(onClick, 800))
  </script>

@zvzuola 好吧,我犯了一个基础的错误,但是你这种写法的话是不是有点累赘,要多声明一个方法,这是最佳的解决办法么?(我觉得我改写的方法也挺好的)
还有我想问问,这个防抖方法是一般是怎么使用的