If you're looking to add a timeout function to XmlHTTPRequest object and determine offline mode for browsers lacking navigator.onLine support, one approach is to extend the object with a specific method. Below is an example of how Ajax timeouts were implemented on a website using the Prototype library. In this implementation, after 10 seconds (10,000 milliseconds), the call is aborted and the onFailure method is triggered.
/**
* Monitoring AJAX requests for timeouts
* Adapted from: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/
*
* Usage: If an AJAX call surpasses the specified time limit, the onFailure method (if defined) will be executed with an error code.
*
*/
var xhr = {
errorCode: 'timeout',
callInProgress: function (xmlhttp) {
switch (xmlhttp.readyState) {
case 1: case 2: case 3:
return true;
// Cases 4 and 0
default:
return false;
}
}
};
// Global responders for all AJAX requests
Ajax.Responders.register({
onCreate: function (request) {
request.timeoutId = window.setTimeout(function () {
// Abort the AJAX request if it's still active after the timeout period
if (xhr.callInProgress(request.transport)) {
var parameters = request.options.parameters;
request.transport.abort();
// Trigger the onFailure method if specified during AJAX object creation
if (request.options.onFailure) {
request.options.onFailure(request.transport, xhr.errorCode, parameters);
}
}
},
// Set timeout to 10 seconds
10000);
},
onComplete: function (request) {
// Clear the timeout as the request completed successfully
window.clearTimeout(request.timeoutId);
}
});