Pergunta

Eu configurei uma atualização da página de Ajax com setInterval. De tempos em tempos, o servidor é tão lento que uma nova solicitação é iniciada antes da conclusão da anterior.

Como posso impedir isso?

Foi útil?

Solução

Use um valor de tempo limite mais curto que o seu intervalo de atualização. Quando a solicitação se aproxima, ele chamará o manipulador de erros, para que você precise diferenciar os erros de tempo e outros tipos de erros no manipulador.

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

Documentos em jquery.com. Exemplo acima da mesma fonte, mas com o valor de tempo limite agregado.

Outras dicas

Use o setTimeout, inicie outro setTimeout somente após o recebimento do resultado da solicitação AJAX. Dessa forma, uma atualização só acontece após o período especificado desde a última atualização.

Instead of using a fixed, hard coded interval: Trigger the next refresh as the last step of handling the current one, e.g. in the "Success" (or "Complete") event callbacks.

You could add a variable that keeps track of the time the current request was sent, so that you can calculate a dynamic delay:

  1. take current time T1
  2. send asynchronous request
  3. other stuff happens...
  4. asynchronous request returns, callback executes
  5. subtract T1 from current time
  6. if result < your desired request interval, set delay value > 0
  7. if result >= your desired request interval, set delay value = 0
  8. call setTimeout with the delay value, initiating the next cycle

What I can tell you is, use a flag in your code. Like (not what I actually recommend just 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 that, its primitive but you will avoid race conditions. Regards.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top