Skip to content

Instantly share code, notes, and snippets.

@mcalavera81
Last active August 11, 2021 22:54
Show Gist options
  • Save mcalavera81/0beafa4a8f0f4d53778abf04ffea06fe to your computer and use it in GitHub Desktop.
Save mcalavera81/0beafa4a8f0f4d53778abf04ffea06fe to your computer and use it in GitHub Desktop.
exponential back-off algorithm
async function getChatRoomWithRetries(id: string, maxDelayMs = 32, maxRetries = 10): Promise<ChatRoom> {
return new Promise<ChatRoom>(async (resolve, reject) => {
let retryCount = 0;
let delayMs = 1000;
while (true) {
try {
return resolve(GetChatRoom({ id }));
} catch (e) {
if (retryCount++ > maxRetries) return reject(e);
await new Promise((resolve) => {
let actualDelayMs;
if ('Retry-After' in e.response.headers) { // #A
actualDelayMs = Number(e.response.headers['Retry-After']) * 1000;
} else {
actualDelayMs = delayMs + (Math.random() * 1000); // #B
}
return setTimeout(resolve, actualDelay);
});
delayMs *= 2;
if (delayMs > maxDelayMs) delayMs = maxDelayMs;
}
} });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment