Code: Retry after timeout

Chapter 8 - Ajax Optimization

If your requests time out, you should retry them. Depending on your timeout time and user tolerance, you should retry your Ajax request a few times before presenting an error dialog to the user. If the user does encounter retries, it would be wise to keep track of that situation and, if possible, transmit statistics about network problems back to your site.

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

function responseTimeout(xhr)
{
    g_abort = true;
    xhr.abort( );
    if (g_retries < 3)
    {
        sendAjaxRequest( );
        g_retries++;
    }
}