Is it possible to abort a synchronous XmlHttpRequest?

I have written a JavaScript function that asynchronously calls a web service using XmlHttpRequest. I have been asked to make this function finish its work before the page is rendered.

I thought I could make the AJAX request synchronous but I don't want this to make the page hang too long - I'd like to abort the request after, say, 1 second if a response isn't received.

Is it possible to abort a synchronous XmlHttpRequest?


You can't:

http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX sais: "Synchronous AJAX (Really SJAX -- Synchronous Javascript and XML) is modal which means that javascript will stop processing your program until a result has been obtained from the server. While the request is processing, the browser is effectively frozen. The browser treats the call like an alert box or a prompt box only it doesn't wait for input from the user, but on input by the remote server"

Once the browser runs the sync request, it will wait until it will get a response.


First of all, synchronous AJAX calls are evil because they are blocking the whole JavaScript browser engine (which you are aware of).

Is simply doing the call asynchronously and discarding the result if it arrives later than after a second is not enough? If you really want to wait for the result you can still use setTimeout() (jQuery for convenience, not required):

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

With this approach you are not blocking the browser while still you don't have to wait for the AJAX call.


XMLHttpRequest support abort method, you can get more details about it here: http://www.w3.org/TR/XMLHttpRequest/#the-abort-method

But you need to check how many browserы support it. For example, abort was introduced in Windows Internet Explorer 7 and above.

Before or after calling send() method of XMLHttpRequest object you can setup a timer for n-seconds delay which will interrupt an asynchronous operation which is in progress.

链接地址: http://www.djcxy.com/p/55336.html

上一篇: 同步XMLHttpRequest警告和<script>

下一篇: 是否有可能中止同步XmlHttpRequest?