erichynds

Hi, I'm Eric Hynds, a front-end website developer living outside of Boston, Massachusetts. I'm passionate about developing functional, standard-compliant, and user-friendly websites.

Posts Tagged ‘javascript’

Using Deferreds in jQuery 1.5

Monday, January 31st, 2011

Deferreds, new in jQuery 1.5, decouple logic dependent on the outcome of a task from the task itself. They’re nothing new to the JavaScript scene; Mochikit and Dojo have implemented them for some time, but with Julian Aubourg’s AJAX rewrite landing in 1.5, deferreds in jQuery was the logical next step. With deferreds, multiple callbacks can be bound to a task’s outcome, and any of these callbacks can be bound even after the task is complete. The task in question may be asynchronous, but not necessarily.

What’s more, deferreds are now built-into $.ajax() so you’ll get them automatically. Handlers can now be bound like this:

// $.get, an ajax request, is asynchronous by default.
var req = $.get('foo.htm')
   .success(function( response ){
      // do something with the response
   })
   .error(function(){
      // do something if the request failed
   });
 
// this might execute before the $.get() above is complete
doSomethingAwesome();
 
// something additional to execute upon success, which might, or might not,
// have fired by now.  With $.ajax deferreds built-in, it doesn't matter.
req.success(function( response ){
   // do something more with the response
   // this will fire when success normally fires, or fire immediately
   // if prior success callbacks have already fired
});

We are no longer limited to one success, error, or complete handler anymore, and instead of simple callback functions, these hooks are now self-managed first-in, first-out callback queues.

As shown in the example above, callbacks may be attached even after the AJAX request – or any observable task – has completed. For code organization this is great; the days of long unwieldy callbacks may be over. It’s almost as if $.queue() meets pub/sub. (more…)

A Recursive setTimeout Pattern

Monday, October 18th, 2010

Colin Snover wrote a good article about why he thinks setInterval is considered harmful:

  1. setInternval ignores errors. If an error occurs in part of your code, it’ll be thrown over and over again.
  2. setInterval does not care about network latency. When continuously polling a remote server for new data, the response could take longer than the interval amount, resulting in a bunch of queued up AJAX calls and an out-of-order DOM.

The solution is to recursively call a named function within setTimeout, which guarantees that your logic has completed before attempting to call it again. At such, this also doesn’t guarantee that your logic will occur on a regular interval. If you want new data every 10 seconds and it takes 15 for your response to come back, you’re now behind by 5 seconds. Colin notes that you can adjust your delay if need be, but you shouldn’t really care as JavaScript timers are not accurate to begin with.

So how to do this? Consider an AJAX poller as this is a common use case:

// old and busted - don't do this
setInterval(function(){
   $.ajax({
       url: 'foo.htm',
       success: function( response ){
          // do something with the response
       }
   });
}, 5000);
 
 
// new hotness
(function loopsiloop(){
   setTimeout(function(){
       $.ajax({
           url: 'foo.htm',
           success: function( response ){
               // do something with the response
 
               loopsiloop(); // recurse
           },
           error: function(){
               // do some error handling.  you
               // should probably adjust the timeout
               // here.
 
               loopsiloop(); // recurse, if you'd like.
           }
       });
   }, 5000);
})();

I’m doing three things here:

(more…)