Skip to content

Function: debounce()

ts
function debounce<TArgs>(
   fn, 
   delay, 
immediate?): DebouncedFunction<TArgs>;

Creates a debounced function that waits for the specified delay after the last call before executing. 创建一个防抖函数,在最后一次调用后等待指定延迟时间再执行。

Type Parameters

Type Parameter
TArgs extends any[]

Parameters

ParameterTypeDescription
fn(...args) => voidThe function to wrap. / 要包装的函数
delaynumberThe delay time (in milliseconds) before the function is executed. / 函数执行前的延迟时间(毫秒)
immediate?booleanWhether to execute the function immediately on the first call. / 是否在第一次调用时立即执行函数

Returns

DebouncedFunction<TArgs>

The wrapped debounced function. / 包装后的防抖函数

Example

ts
const log = debounce((msg) => console.log('debounced:', msg), 300)
log('hello')
log('world')
log.flush() // => 'debounced: world'
log.cancel()
log.pending() // => false

Since

1.2.0

Released under the MIT License.