I really appreciate lodash for its debugging and throttle functionality. I believe that I am well versed in use cases and have implemented them many times.
However, depending on the requirements, there can be a significant and difficult error error with _.debounce functions with arguments. This is the following:
Suppose you have a debounce function called debounceFn that takes one argument and has a debounce interval of 1000 ms.
- 100ms:
debounceFn(1) - 200ms:
debounceFn(2) - 300 ms:
debounceFn(2) - 400ms:
debounceFn(1) - 500ms:
debounceFn(1)
In the end, the child function is called with argument 1. This is great for resizing events in which you care only about the last value, but what if you need separate queues that depend on the arguments? That is, instead of the process called with argument 1, the process is called with argument 1 and with argument 2, but only once is called (because both of them are debounced).
As an extended and slightly more complex example, consider the combination of the arguments below, where the combination creates a unique queue.
actual conclusion:
desired output (the order of the first two outputs can be reversed)
a: apple b: bananaa: apple b: orangea: lime b: kiwi
var process = function(a, b) { document.writeln('a: ' + a + ' b: ' + b); }; var debounceProcess = _.debounce(function(a, b) { process(a, b); }, 1000); setTimeout(function() { debounceProcess('apple', 'orange'); }, 100); setTimeout(function() { debounceProcess('apple', 'banana'); }, 200); setTimeout(function() { debounceProcess('apple', 'orange'); }, 300); setTimeout(function() { debounceProcess('lime', 'kiwi'); }, 400);
<script src="https://cdn.rawgit.com/lodash/lodash/4.6.1/dist/lodash.min.js"></script>
I have seen many questions about _.debounce accepting an argument. This is no longer an interesting question, therefore - how do you create separate debounce queues?
What is an elegant way (simple, easy to read code) to accomplish this with the Lodash _.debounce function, the Lodash library, and JavaScript capabilities? Perhaps a combination of _.debounce and _.memoize (I tried to wrap _.debounce with _.memoize, but you will need to learn to understand memoize further). Or perhaps the function hash of the arguments and create a new _.debounce queue for each combination of arguments?
ryanm source share