Skip to content

Instantly share code, notes, and snippets.

@argentinaluiz
Created August 15, 2023 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save argentinaluiz/7c1316d242b933d3cd2c19311c09a34c to your computer and use it in GitHub Desktop.
Save argentinaluiz/7c1316d242b933d3cd2c19311c09a34c to your computer and use it in GitHub Desktop.
// 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