主题
debounce
js
_.debounce(func, [wait=0], [options={}])
创建一个去抖动函数,该函数将调用 func
延迟到自上次调用去抖动函数以来已过去 wait
毫秒之后。debounced 函数带有一个 cancel
方法来取消延迟的 func
调用和一个 flush
方法来立即调用它们。提供 options
以指示是否应在 wait
超时的前沿和/或后沿调用 func
。func
使用提供给去抖动函数的最后一个参数来调用。对去抖动函数的后续调用将返回最后一次 func
调用的结果。
¥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.
注意:如果 leading
和 trailing
选项为 true
,则仅当在 wait
超时期间多次调用去抖动函数时,才会在超时的尾端调用 func
。
¥Note: If leading
and trailing
options are true
, func
is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during the wait
timeout.
如果 wait
是 0
且 leading
是 false
,则 func
调用将推迟到下一个刻度,类似于 setTimeout
,超时为 0
。
¥If wait
is 0
and leading
is false
, func
invocation is deferred until to the next tick, similar to setTimeout
with a timeout of 0
.
有关 _.debounce
和 _.throttle
之间差异的详细信息,请参阅 David Corbacho 的文章。
¥See David Corbacho's article for details over the differences between _.debounce
and _.throttle
.
新增于
¥Since
0.1.0
参数
¥Arguments
func
(函数):要防抖的函数。¥
func
(Function): The function to debounce.[wait=0]
(数值):要延迟的毫秒数。¥
[wait=0]
(number): The number of milliseconds to delay.[options={}]
(对象):填充长度。¥
[options={}]
(Object): The options object.[options.leading=false]
(布尔):指定在超时的前沿调用。¥
[options.leading=false]
(boolean): Specify invoking on the leading edge of the timeout.[options.maxWait]
(数值):func
在调用之前允许延迟的最大时间。¥
[options.maxWait]
(number): The maximum timefunc
is allowed to be delayed before it's invoked.[options.trailing=true]
(布尔):指定在超时的后沿调用。¥
[options.trailing=true]
(boolean): Specify invoking on the trailing edge of the timeout.
返回
¥Returns
(函数):返回新的去抖动函数。
¥(Function): Returns the new debounced function.
示例
¥Example
js
// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', _.debounce(sendMail, 300, {
'leading': true,
'trailing': false
}));
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);