Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
LegendLeo opened this issue Sep 22, 2018 · 2 comments
Open

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

LegendLeo opened this issue Sep 22, 2018 · 2 comments

Comments

@LegendLeo
Copy link

防抖
这个示例的展开赋值...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>
@zvzuola
Copy link

zvzuola commented Sep 25, 2018

@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>

@LegendLeo
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants