Code: Timeout mechanism

Chapter 8 - Ajax Optimization

First, consider the simple fact that an Ajax request may not return. Make sure you or your Ajax library employs a timeout mechanism. If you need to do it yourself, just set a timer to fire after a set period of time - say, five seconds - to abort the connection in progress.

var g_abort = false;
var xhr = createXHR( );
if (xhr)
{
    xhr.open("GET","sayhello.php",true);
    var timeout = setTimeout(function ( ){g_abort=true;xhr.abort( );},5000);
    xhr.onreadystatechange = function( ){responseCallback(xhr,timeout);};
    xhr.send( );
}

You will notice the inclusion of a g_abort variable. This is added in because when the XHR is aborted, the onreadystatechange function will be called with a readyState of 4. It is vital to ensure that the g_abort variable is set to false before processing incomplete data.