Synchronous ajax call with timeout

New to ajax, so ask a very simple question.

- It is impossible to make a synchronous ajax call (async: false) with a timeout set on it.?

http://www.ajaxtoolbox.com/request/

The timeout works fine with an asynchronous call, although in my application, but for one specific scenario, I need a synchronous call (javascript should really wait until it hears from the server), and this also works fine. But I need to process the scenario when the server can take a lot of time, and the ajax timeout can be called.

Is there any other standard documentation for ajax that I could name?

thanks

+4
source share
2 answers

Basically, during ajax synchronous request, the browser is blocked and javascript cannot be executed while the browser is blocking. Because of this, jQuery cannot abort an ajax request after a set timeout, because jQuery is javascript, and javascript cannot be executed while the browser is blocking. This is the main disadvantage of synchronous ajax.

Anytime you may need a synchronous request, you should instead use asynchronous code with what should happen after the callback, as shown below:

$.ajax({ url : 'webservices.php', timeout: 200, dataType : 'json', data : { 'cmd' : 'ping', }, success : function(data, textStatus) { $.ajax({ url : 'webservices.php', async: false, dataType : 'json', data : { 'cmd' : 'feedback', 'data' : data, 'userinfo' : window.dsuser }, success : function(data, textStatus) { // success! Status("Thanks for the feedback, " + window.dsuser.user + "!"); } }); }, error : function(jqhdr, textStatus, errorThrown) { Status("There was trouble sending your feedback. Please try again later"); } }); 
+1
source

I do not consider it possible to set a timeout on a synchronous call. When you set "async: false", I believe that the browser is really blocked while waiting for a response. You should use only synchronous request if absolutely necessary for you (due to browser blocking).

0
source

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


All Articles