Think that you’re only hitting that key on your keyboard only once as you type? That’s not actually the case.
One Keystroke Is Actually Many
When you press a key on your keyboard, you expect one signal to be sent to your computer each time you press a key. The fact is, your “single” key press ‘bounces’ on the contact multiple times before settling. This causes multiple signals to be sent for each key press.
The bounces are so fast that they are imperceptible to humans but it is enough for a computer to register multiple input signals. The process of ‘debouncing’ ensures that only one signal is sent by only allowing one signal to be registered within a given period of time.
The concept of debouncing in also applicable in software.
Debouncing allows you to schedule a function to run only after it hasn’t been scheduled to run for a minimum amount of time. This can be useful to prevent multiple unnecessary repetitions of the same function. For example, imagine a textfield with typeahead suggestions. If, instead of calling the database for the suggestions after every keypress, you debounced the call by 300 milliseconds, you would only query the database after the user has paused their typing.
Debounce Queue Processing
We can use debouncing to asynchronously build up a queue of actions, or objects to be acted upon, and only when the queue is done being filled, perform the necessary actions.
In the example, try pressing a button. Now, try pressing a bunch of buttons really quickly.
When a button is pressed, it inserts the corresponding person’s data into the persons_queue, then it debounces a call to the controller’s processQueue function with a timeout of 1000 ms. After you’ve stopped pressing buttons for at least one second, processQueue will run, and print out a sample SQL query that combines what would have been many databases calls into one. (WARNING: Creating actual SQL queries on the client side is a horrible idea. This is just an example.)
I’ve used this Debounce Queue Processing technique to significantly improve performance on one of our projects.