Back to menu

Delayed Callback For jQuery


A lot of the time when you bind an action to a text input, you don't really want it to fire after every single change, you want it to fire after no change has been made for a certain length of time. This indicates the user has finished, and it's safe to give them some feedback knowing that it probably won't distract them. It's also beneficial if the action involves an AJAX call to be make a minimal number of requests to your server, which entails waiting until the user has finished before doing anything.

A delayed action isn't particularly hard to implement, but it's also not a one-liner: it involves setting up a timer and cancelling it if the user starts typing again, and you also need to save some state data to make sure things like the `this' scope is set and making sure the event object is passed on. Therefore it makes a useful plugin.

This plugin is very simple to use, it's a single call where you set your callback and optionally: your timeout (default 500 (ms)), laziness (i.e. does the callback need to fire if the text is the same as it was the last time the callback fired?), and 'data', which you can send through the callback if you need. The callback then receives the event and the data (which will be undefined if you didn't provide any), and has `this' set as expected.

Example call:

$('#some_element').delayedAction( function(e, data) {
  alert('You typed ' + $(this).val());


Download the: full source or minified source


This has the lazy attribute unset, so it will re-fire every time the input is changed, regardless of whether the input is the same as the last time it was fired. (hint: try typing 'a' then quickly pressing backspace, note that on this one the output fades in again whereas on the first it doesn't).
This one has some extra data sent through the callback and also demonstrates that the event object is still accessible, as usual.
We can also handle a stack of them fine. This is a silly example where each password input is handled by a single callback which doesn't differentiate between them.