Is it possible to abort a synchronous XmlHttpRequest?

前端 未结 4 1904
渐次进展
渐次进展 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: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.

提交回复
热议问题