Ignoring Old Asynchronous Asynchronous Requests

I have a custom javascript autostart script that gets to the server with several asynchronous ajax requests. (Each time you press a key).

I noticed that sometimes an earlier ajax request will be returned after later requests that will interfere with things.

Now I am processing this, since I have a counter that increments for each ajax request. Requests that return with a lower score are ignored.

I wonder: Is this right? Or is there a better way to solve this problem?

Thanks in advance,

Travis

+4
source share
1 answer

You can save the "global" currentAjaxRequest , which contains the structure of the last XHR request. Then you can abort to execute the current request when creating a new one.

For instance:

 var currentAjaxRequest = null; function autoCompleteStuff() { if(currentAjaxRequest !== null) { currentAjaxRequest.abort(); } currentAjaxRequest = $.get(..., function(...) { currentAjaxRequest = null; ... }); } 

To avoid name conflicts, wrap this in an anonymous, instantly executed function, if necessary.

+8
source

Source: https://habr.com/ru/post/1304403/


All Articles