Skip to content

Instantly share code, notes, and snippets.

@IlyaIvanchikov
Created October 12, 2025 13:38
Show Gist options
  • Select an option

  • Save IlyaIvanchikov/cf72bb3b7c34b89f1a99264cab2c70b0 to your computer and use it in GitHub Desktop.

Select an option

Save IlyaIvanchikov/cf72bb3b7c34b89f1a99264cab2c70b0 to your computer and use it in GitHub Desktop.
// простая функция-пауза
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
/**
* Повторяет выполнение асинхронной операции с линейным ростом задержки
* @param {Function} operation - асинхронная функция, которую нужно выполнить
* @param {number} maxAttempts - максимальное количество попыток
* @param {number} baseDelay - начальная задержка (в мс)
* @param {number} step - насколько увеличивать задержку после каждой ошибки
*/
async function retryWithLinearDelay(operation, maxAttempts = 3, baseDelay = 1000, step = 500) {
let attempt = 1;
while (attempt <= maxAttempts) {
try {
// пробуем выполнить задачу
return await operation();
} catch (err) {
// если исчерпали все попытки — кидаем ошибку дальше
if (attempt === maxAttempts) throw err;
// считаем задержку: база + шаг * (номер попытки - 1)
const delay = baseDelay + step * (attempt - 1);
console.log(`Ошибка на попытке ${attempt}, повтор через ${delay}мс...`);
// ждём рассчитанное время
await sleep(delay);
// переходим к следующей попытке
attempt++;
}
}
}
// пример использования
async function fetchData() {
return retryWithLinearDelay(async () => {
const res = await fetch('https://api.example.com/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}, 4, 1000, 800);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment