PART II
Chapter 6: Networking Considerations 233
onTimeout : showFailure
/* show failure is some user defined function */
};
In the _makeRequest() method, a timeout is defined based upon these settings:
if (request.async)
{/* bind the success callback */
request.xhr.onreadystatechange = function ()
{AjaxTCR._handleResponse(request);};
/* set a timeout if set */
if (request.timeout)
request.timeoutTimerID = window.setTimeout(
function(){AjaxTCR.comm._timeoutRequest(request);}, request.timeout);
As you can see here, the method now sets a timeout to be the specified time and sets
a property, timeoutTimerID, in the request. In the case of a successful response, the
_handleResponse() method will be called and it will clear the timeout so that the callback
is never invoked.
/* clear any timeouts */
if (response.timeoutTimerID)
clearTimeout(response.timeoutTimerID);
However, in the case where it does call the _timeoutRequest() method, the code must
first make sure that the request wasn’t previously finished or unsent. If not, it aborts the
request and then finally calls the user-specified timeout callback function.
_timeoutRequest : function(request) {
/* make sure it is a proper time to abort */
if (request.xhr.readyState != AjaxTCR.comm.DONE &&
request.xhr.readyState != AjaxTCR.comm.UNSENT)
{
/* abort the request */
AjaxTCR.comm.abortRequest(request);
request.onTimeout(request); /* invoke user defined timeout callback */
}
}
You can see a simple version of the timeout feature in action at http://ajaxref.com/ch6/
simpletimeout.html as well as in Figure 6-1.
Retries
In the previous case, we handled the idea of waiting for a request that has exceeded a specific
time threshold to return. However, it is a bit harsh to simply cancel a request and fail upon
the first problem encountered. Maybe it would be a bit wiser to retry the request a few times
first before giving up. For example, if the response does not return in a few seconds, you
might abort the request and reissue it. Of course, after a certain number of retries the request
would ultimately be aborted. To specify that retries should occur, set retries to a number of