I wrote a JavaScript function that asynchronously calls a web service using XmlHttpRequest. I asked this function to complete its work before the page displays.
I thought I could make the AJAX request synchronous, but I do not want this to hang for too long - I would like to cancel the request after, say, 1 second if no response has been received.
Is it possible to abort synchronous XmlHttpRequest?
You can not:
http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX sais: " AJAX ( SJAX - Javascript XML) , , javascript , . , . , , , "
, , .
, AJAX , JavaScript ( ).
, , , ? , setTimeout() (jQuery , ):
setTimeout()
var result; var xhr = $.ajax('/url', function(response) { result = response; }); setTimeout(function() { if(result) { //AJAX call done within a second, proceed with rendering } else { //One second passed, no result yet, discard it and move on xhr.abort(); } }, 1000);
, AJAX.
XMLHttpRequest support abort, : http://www.w3.org/TR/XMLHttpRequest/#the-abort-method
XMLHttpRequest
abort
, . , abort Windows Internet Explorer 7 .
send() XMLHttpRequest n , .
send()
IE. timeout.
the code below worked for me
xmlhttp.open("method","url",false); xmlhttp.timeout="time in ms"; xmlhttp.ontimeout=function(){}; xmlhttp.send();