Luke Eller
Luke Eller

Reputation: 627

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?

Upvotes: 5

Views: 8720

Answers (4)

Jithin K George
Jithin K George

Reputation: 19

It is possible in IE.Use the timeout property.

the code below worked for me

xmlhttp.open("method","url",false);
xmlhttp.timeout="time in ms";
xmlhttp.ontimeout=function(){};
xmlhttp.send();

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340953

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.

Upvotes: 1

Utkarsh Panwar
Utkarsh Panwar

Reputation: 131

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.

Upvotes: 1

Vlad Balmos
Vlad Balmos

Reputation: 3412

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.

Upvotes: 5

Related Questions