util.debounce(fn, wait[, options])
fn<Function> 去抖动的函数。wait<integer> 延迟fn的毫秒数。options<Object>leading<boolean> 当true被触发时,会在新的防抖窗口开始时立即调用fn。默认值:false。rejectOnCancel<boolean> 当true(被后续调用取代的调用)因AbortError拒绝时。默认值:false。signal<AbortSignal> 一个AbortSignal,在中止时会取消挂起的调用并阻止未来的调用。
- 返回:<Function> 防抖函数
创建一个函数,该函数会延迟调用 fn,直到自最近一次调用起已经过去 wait 毫秒。防抖函数会返回一个 <Promise>,用于 fn 返回的值。如果 fn 抛出错误或返回一个拒绝的 promise,那么返回的 promise 会以相同的原因被拒绝。
🌐 Creates a function that delays calling fn until wait milliseconds have
elapsed since the most recent invocation. The debounced function returns a
<Promise> for the value returned by fn. If fn throws or returns a rejected
promise, the returned promise is rejected with the same reason.
当防抖函数在延迟时间到期前被调用多次时,fn 会接收到最近一次调用的参数。默认情况下,所有调用的 Promise 都会以该调用的结果来解决或拒绝。如果 options.rejectOnCancel 是 true,被取代的调用的 Promise 会以一个 AbortError 拒绝。
🌐 When the debounced function is called more than once before the delay expires,
fn receives the arguments from the most recent call. By default, the promises
from all calls resolve or reject with the result of that invocation. If
options.rejectOnCancel is true, the promises from superseded calls reject
with an AbortError instead.
当 options.leading 是 true 时,在防抖窗口中的第一次调用会立即触发 fn。在该窗口期间的调用会被延迟,直到距离最近一次调用已经过去了 wait 毫秒。只有在窗口期间再次调用防抖函数时,才会有尾随调用。窗口在 fn 被调用之前就开始了,所以如果递归调用或者在异步 fn 等待期间的调用发生在延迟结束之前,它们都算在同一个窗口内。这也适用于同步 fn 返回之后但在延迟结束之前进行的调用。
🌐 When options.leading is true, the first call in a debounce window invokes
fn immediately. Calls made during that window are delayed until wait
milliseconds have elapsed since the most recent call. A trailing invocation
only occurs if the debounced function was called again during the window.
The window begins before fn is invoked, so recursive calls and calls made
while an asynchronous fn is pending are part of the same window if they occur
before the delay expires. This also applies to calls made after a synchronous
fn returns but before the delay expires.
如果 options.signal 被中止,挂起和将来的调用会以 AbortError 拒绝,并且信号的原因会被设置为错误的 cause,而这些调用不会调用 fn。如果信号已经被中止,debounce() 会抛出一个 AbortError。
🌐 If options.signal is aborted, pending and future calls reject with an
AbortError, with the signal's reason set as the error's cause, and fn is
not invoked by those calls. If the signal is already aborted, debounce()
throws an AbortError.
返回的函数有以下属性:
🌐 The returned function has the following properties:
cancel([reason])取消当前的防抖窗口。它的待处理承诺会被AbortError拒绝。如果提供了,reason会被设置为错误的cause。flush()取消延迟并立即调用fn。如果没有待执行的调用,则不会有任何效果。pending<Promise> | <null> 这是当前防抖窗口中最近一次调用返回的 Promise,如果没有待处理的调用,则为null。pendingCount<integer> 是在当前防抖时间窗口中等待调用的次数。ref()会让挂起和未来的超时保持 Node.js 事件循环活跃。返回防抖函数。unref()允许在超时未结束时退出事件循环。这同样适用于未来的超时。返回防抖函数。
当调用时,fn 的 this 值是防抖函数。在一次尾随调用之后,即使 fn 返回的 Promise 仍在挂起,一个新的防抖窗口也可以开始。防抖函数会保留 fn 的 name 和 length。
🌐 When invoked, fn has the debounced function as its this value. After a
trailing invocation, a new debounce window can begin even if a promise returned
by fn is still pending. The debounced function preserves the name and
length of fn.
import { setTimeout as wait } from 'node:timers/promises';
import { debounce } from 'node:util';
const fn = debounce(async (value) => {
await wait(100);
return value;
}, 50);
const first = fn(1);
const second = fn(2);
console.log(await first); // 2
console.log(await second); // 2 防抖函数可以在一段时间不活动后触发一个动作。每次调用都会重置超时:
🌐 A debounced function can be used to trigger an action after a period of inactivity. Each call resets the timeout:
const { debounce } = require('node:util');
const onInactivity = debounce(() => {
console.log('No activity for 5 seconds');
}, 5_000).unref();
process.stdin.on('data', (data) => {
console.log(`Received ${data.length} bytes`);
onInactivity();
});
// Start the initial inactivity timeout.
onInactivity();