Lodash _.debounce 与队列组合?
有没有办法保留调用去抖函数的所有参数,将它们保存在队列中,然后触发单个批处理操作?
例如:
const debounceWithQueue = _.debounce(myFn, 1000);
debounceWithQueue(1);
debounceWithQueue(2);
debounceWithQueue(3);
一秒钟过去后,我希望使用参数 [1, 2, 3]
执行我的函数 myFn
myFn([1, 2, 3]);
另外,如果满足以下任一条件,是否可以触发1 秒过去了或队列已达到一定大小(记录 debounceWithQueue 函数被调用的次数
Is there a way to keep all the arguments the debounced function has been called with, keep them in a queue and then fire a single batch action ?
For example:
const debounceWithQueue = _.debounce(myFn, 1000);
debounceWithQueue(1);
debounceWithQueue(2);
debounceWithQueue(3);
and after one second has passed I want my function myFn
to be executed with an argument [1, 2, 3]
myFn([1, 2, 3]);
Also, is it possible to fire if either 1 second has passed OR the queue has reached a certain size (keeping count of how many times the debounceWithQueue function has been called
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用将数组保存为队列的函数来包装 _.debounce()。原始函数(
fn
)被runFn
包装,它通过队列调用原始函数,并清除队列。我们将 debounce 应用于 runFn(debounced
函数)。当您在函数上使用
debounceWithQueue
时,会返回一个新函数。每当调用新函数时,它都会对当前参数进行排队,检查参数的长度,如果它们超过最大值,则会刷新debounced
。如果队列未满,则会调用debounced
。注意:我使用剩余参数 (
...a
) 收集参数,这意味着每次调用函数时都会向args
添加一个数组> 数组。您可以通过将fn(args);
更改为fn(args.flat());
将数组的数组展平为单个参数数组,但我认为如果原始函数可以处理数组的数组就更好了。You can wrap
_.debounce()
with a function that holds an array as a queue. The original function (fn
) is wrapped byrunFn
, which calls the original function with the queue, and clear the queue. We apply debounce torunFn
(thedebounced
function).When you use
debounceWithQueue
on a function, a new function is returned. Whenever the new function is called, it queues the current arguments, checks the length of the arguments, and if they are over the maximum, it flushesdebounced
. If the queue is not full,debounced
is called instead.Note: I collect the arguments using rest params (
...a
), which means that every call to the function, adds an array toargs
array. You can flatten the array of array to a single array of arguments, by changingfn(args);
tofn(args.flat());
, but I think that it's better if the original function can handle the array of arrays.