Created
June 11, 2018 11:26
-
-
Save Toliak/98fa28880a4caf042c2aaf658c1ecf64 to your computer and use it in GitHub Desktop.
Download files from `/url/${from}` to `/url/${to}`
This file contains 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
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/"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Хороший скрипт, отлично работает.