Blog

Aug
07
Throttling Interaction with jQuery
by Cary Dunn | Article

If you're new here, you may want to subscribe to our RSS feed. Thanks for visiting!

Expanding on a previous post on $.ajax abort() about throttling user interaction, here are few plugins and techniques I’ve found to be very useful when developing jQuery heaving interfaces.

jquery-debounce
Smart JS Polling
blockUI plugin

Reviews after the jump…

Debounce and Throttle

With all of jQuery’s easy to use selectors it’s easy to overlook the reprocusions of a JS function on CPU usage. Class selecting (in old browsers without native support), chaining, tweening css properties, can all push browser CPU usage to the max when used in quick succession. Binding events to scrolls, mousemove’s, and keypresses highlight the need for some light throttling of functions that won’t limit user experience if delayed an extra 100ms.

In short, throttling will reduce the rate of a repeated event whereas debouncing will ensure that only one signal for a given event is fired within a fixed amount of time. (A much better and detailed explanation can be found here)

As an example, if someone is only able to type at 10 keys/second, what good would it be to fire events sooner than 100ms? You can see how things like autocompletes, keyevents, and scroll updates would require some sort sort of rate limiting.

jQuery Throttle & Debounce Plugin

My favorite plugin for this is jquery-debounce.


$('input[name=suggest]').keyup($.debounce(onKeyUp, 300));


$(window).resize($.throttle(doComplex?omputation, 300));

Smart Polling

In an ideal world, polling doesn’t exist and we are all using push models, but in reality the infastructure for a push service is not worth it in alot of cases and lightweight polling works just fine.

Prototype JS supports an Ajax.PeriodicalUpdater which works beautifully and supports things like decay functions and response logic.

For jQuery i’ve used Smart JS Polling which is a simple extension which gives you a wait time and a function to specify a backup/decay function.

Freeze/Block UI

There are alot of cases in a JS frontend where freezing the UI with a spinner would be less confusing (though more painful…) to the user that some processing needs to take place before they can continue clicking around and launching more actions.

For this, the jQuery blockUI plugin is easy to use and alleviates the clutter from having extra hidden divs and absolute this and that in your views.

No Comments