Todaymade


Use Debouncing For Better App Performance

Posted: 05 Dec 2013 01:15 PM PST

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.

Take a look at my example JSBin code. (I’m using Ember.js in the example, but debounce can be used in any context. The super-useful JavaScript library Underscore also includes a debounce function.)

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.

The post Use Debouncing For Better App Performance appeared first on Todaymade Blog.

 
Tips and Tricks Blogging © 2013. All Rights Reserved. Powered by Blogger
Top