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

13 - Slide in on Scroll #19

Open
ghost opened this issue Jul 18, 2017 · 4 comments
Open

13 - Slide in on Scroll #19

ghost opened this issue Jul 18, 2017 · 4 comments

Comments

@ghost
Copy link

ghost commented Jul 18, 2017

缉熙你好,该程序中的 debounce 防抖 我觉得应该是 throttle 节流

debounce 防抖

debounce 防抖 应该是在用户停止触发某个事件一段时间后,该事件的处理程序被触发。

比如输入用户名时的验证,应该等到用户输入完成,也就是停止输入后才触发,而不是在用户每次输入一段时间后就触发验证程序。用户名有长有短,不能在用户还未输入完成时就提示错误。

throttle 节流

throttle 节流 则是限制事件处理程序被调用的频率,在固定的时间内只会调用一次。

该程序只是为了限制 scroll 事件处理程序被调用的次数,这里应该是 throttle 节流

但我注意看了该程序的作用,确实是限制了 scroll 事件处理程序被调用的次数,那么就是名字起错了。

这里贴一段稍微容易理解的 throttle 节流 函数,该程序中的写法感觉好复杂:

function throttle (func, interval) {
  let startTime = Date.now()

  return function (...args) {
    const currentTime = Date.now()
    if (currentTime - startTime > interval) {
      func(...args)
      startTime = currentTime
    }
  }
}
@soyaine
Copy link
Owner

soyaine commented Jul 18, 2017

@dcfm 多谢,我前天看了一些资料,也没有完全理解这两个函数的区别,所以文章里也没有深入解释。可否贴一下你这段程序的来源?

@ghost
Copy link
Author

ghost commented Jul 19, 2017

@soyaine 额,我也是看了相关的别人的博客之后做的笔记,好像是看了好几篇,然后总结的吧。不过 lodash 里面有这两个函数,你可以去看看源码,但是实现起来就更复杂了。我贴这个代码是因为更容易看懂 throttle 是什么功能,我觉得这思路很好。

@LinFeng1997
Copy link

rxjs和红宝书都有相关的概念,防抖动就是用户在一定时间内点很多次(抖动)只取最近的,节流是一定时间内其他的都不算,只要一个。

@lkangd
Copy link

lkangd commented Sep 7, 2017

你这 throttle 节流的函数这么写会有细节上的问题,interval间隔越大,问题越明显。
1.第一次触发时,函数不会被执行。(解决:增加变量标记是否第一次触发)
2.若最后一次触发没有超过interval也不会触发。(解决:使用setTimeout)

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

3 participants