debounce & throttle 去疑

debounce 防抖,限定操作在一段时间、行为不活动之后发生;延迟执行,如窗口缩放行为、按键输入行为、点击行为,延迟回调;

throttle 节流,只是‘掐住’,限定操作按时间频率周期发生;将高频转为低频,间歇性执行,如滚动加载、点击,阻止回调被触发的太快;

上面两句话,可以完全解惑。

这里有一个在线 debounce & throttle demo,可以点击或移动鼠标感受一下两者之间的区别。

下面是 Underscore/Lodash 中的相关详细描述:

debounce

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

创建一个debounce函数,该函数会延迟/延迟/延迟调用func对象,等待一段时间直到上次debounce函数调用执行完。debounce函数带有一个cancel方法来取消延迟的func对象调用和一个flush方法来立即调用它们。提供选项(options)以指示是否应在延迟事件之前(leading)和/或之后(trailing)调用func。func调用时会传入最后一次提供给 debounce函数的参数。 后续调用的debounce函数返回是最后一次func对象调用的结果。

函数最后一次调用之后等待一段时间,再次执行函数;

即控制用户操作停止到达一段时间之后再次执行。

……基于行为的不活动,去抖

resize, keyup, click,


throttle

Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

创建一个throttle函数,每一段时间内最多只会调用一次 func。被throttled(扼杀)的函数带有一个cancel方法来取消延迟的func调用和一个flush方法来立即调用它们。提供选项(options)以指示是否应在间隔事件之前(leading)和/或之后(trailing)调用func。func对象调用作为最后一次传参提供给throttle函数。调用throttle函数会返回最后一次func调用的结果。

当重复调用函数的时候,至少每隔一段时间,到达时间间隔后再调用一次该函数;控制程序触发频率较高的事件。

……基于时间的频率,节流

scroll, click


[options.leading=true] (boolean): 指定在延迟/节流开始前调用。
[options.trailing=true] (boolean): 指定在延迟/节流结束后调用。


发布了110 篇原创文章 · 获赞 53 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/xianghongai/article/details/79864236