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

如何实现事件的防抖和节流? #11

Open
suukii opened this issue Jul 2, 2020 · 0 comments
Open

如何实现事件的防抖和节流? #11

suukii opened this issue Jul 2, 2020 · 0 comments

Comments

@suukii
Copy link
Owner

suukii commented Jul 2, 2020

节流

节流的核心思想是:如果在定时器的时间范围内再次触发事件,就什么都不做,只有等当前定时器结束后,才能启动新的定时器。
代码思路:用一个 flag 来标识当前是否可以启动定时器,当我们启动一个定时器时,把 flag 设为 false,等这个定时器结束后再把 flag 设为 true。

防抖

每次事件触发时都删除原来的定时器,然后启动一个新的定时器。

加强版防抖

在防抖的情况下,如果事件触发得太频繁,会导致一次响应也没有,但我们希望到了固定时间时必须给用户一个响应。
代码思路:记录上一个定时器结束的时间 last,当事件触发时,计算当前时间与上一个定时器结束时间的差距 now - last,如果时间差大于我们预设的固定时间,就立即执行一次函数。

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

No branches or pull requests

1 participant