Created
August 15, 2023 17:56
-
-
Save argentinaluiz/7c1316d242b933d3cd2c19311c09a34c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cliente | |
const MAX_ATTEMPTS = 3; // Número máximo de tentativas | |
let currentAttempts = 0; // Contador de tentativas | |
let currentInterval = 1000; // Intervalo inicial entre chamadas (em milissegundos) | |
function longPolling() { | |
fetch('/server-endpoint') | |
.then(response => response.json()) | |
.then(data => { | |
if (data && data.length > 0) { | |
// Manipule os dados recebidos do servidor | |
console.log('Novos dados recebidos:', data); | |
// Redefina as tentativas e o intervalo | |
currentAttempts = 0; | |
currentInterval = 1000; | |
} else { | |
// Incrementa o contador de tentativas | |
currentAttempts++; | |
// Aumenta o intervalo entre chamadas a cada tentativa | |
currentInterval *= 2; | |
} | |
// Inicie outro long polling após manipular os dados ou ajustar o intervalo | |
setTimeout(longPolling, currentInterval); | |
}) | |
.catch(error => { | |
console.error('Erro durante o long polling:', error); | |
// Tente novamente após um intervalo em caso de erro | |
setTimeout(longPolling, currentInterval); | |
}); | |
} | |
// Inicie o long polling | |
longPolling(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment