2

I want to send post request via ajax, it has to be very fast like under 100 ms. This page also contains other network requests(even image refresh) in setIntervals.

When the below function is called mainRequest(), I want to stop all other network requests and just send this request. So its fast and high priority request.

function  mainRequest()
{
  stop(); // something like this that stop all network requests immediately
  $.post( "https://example.com", $str ,function(data) {
    console.log(data);
  })
  .fail(function() {
    alert( "error" );
  });
}

I googled and found about request.abort(); , Is there any alternative that generally aborts all request, including image loads.

Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
Gracie williams
  • 1,287
  • 2
  • 16
  • 39
  • 2
    I think "window.stop()" will work for you. This seems to be duplicate of following question- https://stackoverflow.com/questions/117551/javascript-cancel-all-kinds-of-requests – Rahul Raut Mar 07 '19 at 05:40
  • Possible duplicate of [javascript: cancel all kinds of requests](https://stackoverflow.com/questions/117551/javascript-cancel-all-kinds-of-requests) – Louys Patrice Bessette Mar 07 '19 at 05:48

1 Answers1

1

My solution is for XMLHttpRequests requests. The code is based on this question and answers.

So basically you can use a hook that was explained in the question.

// Generate unique id
const generateUID = function () {
  return `id:${Math.random().toString(36).substr(2, 9)}`;
};

// Where we store all requests
let requests = {};

// Intercept all XMLHttpRequest requests
(function (send) {
  XMLHttpRequest.prototype.send = function (data) {
    this.uid = generateUID();
    requests[this.uid] = this;
    this.addEventListener('readystatechange', function () {
      if (this.readyState === 4) {
        delete requests[this.uid];
        console.log("Deleted", this.uid)
      }
    }, false);
    send.call(this, data);
  };
}(XMLHttpRequest.prototype.send));

// Call this to stop active requests
const stopActive = function () {
  for (const key in requests) {
    const request = requests[key];
    console.log(request);
    request.abort();
  }
};
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37