Call (877) SITE-OPT (748-3678)

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)
    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.

Copyright © 2002-2018 Website Optimization, LLC. All Rights Reserved - Free website speed test - Privacy Policy
Last modified: February 19, 2009.

Follow us on: Twitter, Google+, Facebook, Linked In