Question:
Consider the below JavaScript code, which works fine so far, except... ... that it completely ignores the timeout. Why ?I tested it with sleeping 10s in the ashx handler (timeout is set to 5s), and so far it never complained about timeout. I will increase the timeout for production use, of course.
function createXMLHttpRequest()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
function ExecuteSQL(strParameter1, strParameter2, strParameter3)
{
try
{
strParameter1 = encodeURIComponent(strParameter1);
strParameter2 = encodeURIComponent(strParameter2);
strParameter3 = encodeURIComponent(strParameter3);
var x开发者_Python百科hReq = createXMLHttpRequest();
var dtNow = new Date();
var dt = Date.parse(dtNow) + dtNow.getMilliseconds()
var params = "prm1=" + strParameter1 + "&prm2=" + strParameter2 + "&prm3=" + strParameter3 + "&prm4=END";
params = params + "&NoCache=" + dt;
//var URLget = "cgi-bin/RequestData.ashx?NoCache=" + dt + "¶m1=value1¶m2=value2";
var URLpost = "cgi-bin/RequestData.ashx?NoCache=" + dt;
xhReq.open("POST", URLpost, false);
//Send the proper header information along with the request
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("Content-length", params.length);
xhReq.setRequestHeader("Connection", "close");
/*
xhReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
*/
var MAXIMUM_WAITING_TIME = 5000;
var requestTimer = setTimeout(function () {
xhReq.abort();
alert("Request cancelled. \nReason: Timeout (" + MAXIMUM_WAITING_TIME/1000 + "s) exceeded.");
// Handle timeout situation, e.g. Retry or inform user.
}, MAXIMUM_WAITING_TIME);
xhReq.send(params);
if (xhReq.status != 200) {
clearTimeout(requestTimer);
if (xhReq.status == 400)
{
var serverResponse = xhReq.responseText;
alert(unescape(serverResponse));
}
else
alert("XMLHttpRequest Error\nHTTP Status: " + xhReq.status + "\nStatusText: " + xhReq.statusText);
}
else {
clearTimeout(requestTimer);
// Handle error, e.g. Dis
var serverResponse = xhReq.responseText;
alert("Successfully return from execution.");
//alert(unescape(serverResponse));
}
} catch (ex) {
alert("Error in JavaScript-function \"ExecuteSQL\".\nError description: " + ex.Description);
}
} // End Sub ExecuteSQL
I'm going to delete everything that has nothing to do with the timer and see if your problem becomes incredibly obvious.
function something()
{
var requestTimer = setTimeout(function () {
alert("something");
}, 1);
if (something) {
clearTimeout(requestTimer);
}
else {
clearTimeout(requestTimer);
}
}
define this variable var requestTimer outside function ExecuteSQL
You are making a synchronous call using XMLHTTPRequest. Try making it async by changing false to true in the following call:
xhReq.open("POST", URLpost, true);
Currently, due to your sync call the timeout gets cancelled.
精彩评论