Is it possible to abort a synchronous XmlHttpRequest?

前端 未结 4 1861
渐次进展
渐次进展 2021-01-19 01:35

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

相关标签:
4条回答
  • 2021-01-19 01:42

    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.

    0 讨论(0)
  • 2021-01-19 01:43

    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();
    
    0 讨论(0)
  • 2021-01-19 01:50

    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.

    0 讨论(0)
  • 2021-01-19 01:55

    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.

    0 讨论(0)
提交回复
热议问题