Creating a Memoized Debounced Function with Lodash
Bailey Tincher
Backend Dev for Actually Colab#
The ProblemCreating a real-time collaborative text editor is a balance between performance and efficiency. We want keystrokes to appear live to other users, but, practically, what does that actually mean? With some having a typing speed in excess of 5 characters per second, it seems unnecessary to send a request every two-tenths of a second for each keystroke. To reduce the volume of requests being made we can group a series of edits together and send them in chunks. This way, rather than sending 1 character per request, we send groups of 3 or 4 characters instead.
This approach is often referred to as debouncing requests.
#
Initial Approach with LodashCommon utility libraries in JavaScript exist to debounce such as Lodash.
Looking at the signature, it accepts the function to debounce and the number of milliseconds to delay as arguments. This is great and does exactly what it claims. Let's see what this would look like with our text editor.
This seems to do the trick. Though two function calls are made that make a request to our server, only the final one will get executed since it was called before our 500ms debounce window. Let's look at another scenario.
In this case, our user is super fast and switches which editor they are working in and types another character
before our 500ms debounce window. As a result, the first call to update the contents of cell someId
never gets
triggered.
This reflects a key shortcoming with Lodash's debounce. It has no regard for the parameters being passed to the function and instead will simply reset with each call. Unfortunately, none of Lodash's optional parameters for debounce can help us get around this.
#
The Memoized DebounceTo create a debounce function that discriminates based on the parameters being passed to it, we'll need a custom option. Some ideas were discussed on this issue thread that inspired my approach. The thread had some working prototypes, but they were not compatible with TypeScript.
Lodash's TypeScript support is peculiar, but I did my best to work around it.
Now we can put it to use to solve our original problem.
And then we use it just like a normal function!
Unlike the original debouncedEdit
, in this case both requests to edit someId
and otherId
will be completed.