Skip to content

Instantly share code, notes, and snippets.

@Toliak
Created June 11, 2018 11:26
Show Gist options
  • Save Toliak/98fa28880a4caf042c2aaf658c1ecf64 to your computer and use it in GitHub Desktop.
Save Toliak/98fa28880a4caf042c2aaf658c1ecf64 to your computer and use it in GitHub Desktop.
Download files from `/url/${from}` to `/url/${to}`
function downloader (from = 1, to = 5, url) {
if (typeof(url) !== "string") throw;
const INTERVAL = 250; // Интервал между запросами
window.g_timer_timestamp = Date.now();
window.g_counter = from; // Счетчик
window.g_aviable = true; // Если прошлый файл не скачался, новое скачивание не начинается
let f = function() {
window.g_aviable = false; // Блокируем
// AJAX запрос
let xhr = new XMLHttpRequest();
xhr.open("GET", `${url}${window.g_counter}`);
xhr.addEventListener("readystatechange", function() {
if (this.readyState != 4) return 0;
if (xhr.status != 200) {
console.log(xhr.status + ': ' + xhr.statusText);
} else {
// Проверка на длину ответа
if (xhr.response.length < 5) {
console.log(`${url}${window.g_counter} small`);
} else {
// Создаем <a>
let a = document.createElement("a");
a.download = `${window.g_counter}.xml`;
a.href = `data:text/plain;charset=utf-8,${encodeURIComponent(xhr.response)}`;
// Имитируем нажатие ЛКМ
let e = new MouseEvent("click");
e.which = 1;
a.dispatchEvent(e);
}
window.g_aviable = true; // Разблокируем
}
});
xhr.send(); // Получаем
};
let timer = function () {
// Проверка интервала и состояния предыдущего файла
if (!(Date.now() - window.g_timer_timestamp >= INTERVAL && window.g_aviable)) return requestAnimationFrame(timer);
window.g_timer_timestamp = Date.now(); // Обновляем отсчет времени
f(); // Основная функция
window.g_counter++; // Увеличиваем счетчик
if (window.g_counter > to) return 0; // Если цикл выполнен, выходим
requestAnimationFrame(timer); // timer поставлен в очередь на рендер
};
requestAnimationFrame(timer); // timer поставлен в очередь на рендер
}
downloader(1, 5, "/url/");
@Hortule
Copy link

Hortule commented Jun 11, 2018

Хороший скрипт, отлично работает.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment