Interruption of an asynchronous request

Asked

Viewed 391 times

9

What happens when the user, for example, reloads the page with an asynchronous request in progress? Does the server continue to run the script? And how can I interrupt an ongoing request via JS?

1 answer

10


What happens when the user, for example, reloads the page with an asynchronous request in progress?

Depends on the timing. If the request has already been sent to the server, it is processed normally (but, of course, the response will never be delivered to the client). If the request is not out yet, it never reaches the server and is not processed. In general you will fall in the first case, do not know under what circumstances you could fire a request and reload the page even before it is sent.

And how can I interrupt an ongoing request via JS?

Whereas you are wearing XMLHttpRequest, there is a method abort:

// Enviar:
var requisicao = new XMLHttpRequest();
requisicao.open("get", "arquivo.html", true);
requisicao.send();
// CANCELAR:
requisicao.abort();
  • Great answer, but I got a question. If the request is a post, for example, and the server has already received it, even if it aborts it will be processed normally right?

  • 1

    @Caputo I believe so (be it POST, GET or any other verb).

  • Thank you for your reply. I came up with this question / concern because I have a request that takes about 2 min. In this case it is easy for the user to find the error in the page and try to reload it.

  • 1

    Got it @Oeslei. But don’t you have an on-screen indication that there’s something time-consuming going on in the background? If not, it’s always good to put.

  • Yes. It has a Loader in the system for all requests, and for the longest, as in this case, it has a more prominent Loader as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.