jQuery: intervalo de atraso da função Ajax até a execução anterior ser concluída
-
21-08-2019 - |
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?
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:
- take current time T1
- send asynchronous request
- other stuff happens...
- asynchronous request returns, callback executes
- subtract T1 from current time
- if result < your desired request interval, set delay value > 0
- if result >= your desired request interval, set delay value = 0
- 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.