https://segmentfault.com/a/1190000013712277
https://mp.weixin.qq.com/s/Vkshf-nEDwo2ODUJhxgzVA (有图配合理解)
概念
函数节流和函数防抖二者很容易被混淆起来。下面贴英文原文,建议认真阅读: Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called". Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds".
函数防抖:函数在特定的时间内没有再被调用后执行。eg: 输入框频频繁操作 函数节流是从用户停止输入开始计时
函数节流:确保函数特定的时间内至多执行一次。eg: 性能考虑 函数节流是从用户开始输入就开始计时
大部分的完整
debounce
实现还有第三个参数immediate
,表明回调函数是在一个时间区间的最开始执行(immediate
为true
)还是最后执行(immediate
为false
)。一般demo里面是做的最后执行。
防抖一般直接包裹在事件外面。
更多阅读
debounce逐步优化实现:https://juejin.im/post/5c270ae16fb9a049bb7c69c2
如果debounce函数要返回值的话就比较复杂了。
Throttle 用时间戳+定时器配合实现:https://mp.weixin.qq.com/s/Vkshf-nEDwo2ODUJhxgzVA
保证了第一次触发事件就能立即执行事件处理函数和每隔delay时间执行一次事件处理函数。