JQuery: ajax function delay interval until completion of previous run

I installed an AJAX page update using setInterval . From time to time, the server is so slow that a new request is initiated before the previous one has completed.

How can I prevent this?

+3
source share
4 answers

Use a timeout value that is shorter than your refresh interval. When the request expires, it is called by the error handler, so you will need to distinguish between time errors and other types of errors in the handler.

 $.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   timeout: 5000, /* ms or 5s */
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

Docs on jquery.com. The example above is from the same source, but with a timeout value added.

+6

setTimeout, setTimeout AJAX. , .

+2

: , . "" ( "" ).

, , :

  • T1
  • ...
  • ,
  • T1
  • < , > 0
  • result >= , = 0
  • setTimeout ,
+2

What can I tell you, use a flag in your code. For example (not what I actually recommend just for a simple example)

var isWorking = false;
function doRequest(){
  if(isWorking) return;
  isWorking = true;
  $.ajax({
    ...,
    success: workWithResponse
  });
}

function workWithResponse(){
  /* doAnythingelse */
  isWorking = false;
}

setInterval(doRequest,1000);

Something like this, its primitive, but you will avoid the race conditions. Regards.

+2
source

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


All Articles