Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 387
Luke Eller Avatar asked Sep 22 '11 07:09

Luke Eller


2 Answers

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.

like image 126
Vlad Balmos Avatar answered Sep 23 '22 19:09

Vlad Balmos


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.

like image 38
Tomasz Nurkiewicz Avatar answered Sep 22 '22 19:09

Tomasz Nurkiewicz