Событие Keyup срабатывает при любом нажатии клавиши.
Попробуйте так:
window.addEventListener('load', function () {
var MIN_CHARACTERS_NUMBER = 1;
var DELAY = 300;// ms
var nameInput = document.querySelector('.name_input'),
hugeList = document.getElementById('huge_list');
if (!nameInput || !hugeList) {
return void console.error('Input or List not found');
}
var getRequestUrl = function (queryString) {
return 'query.php?query=' + encodeURIComponent(queryString) + '&data=' + new Date();
};
var abortController,
timer = 0;
nameInput.addEventListener('input', function (event) {
var value = this.value.trim();
if (value.length < MIN_CHARACTERS_NUMBER) {
return;
}
clearTimeout(timer);
timer = setTimeout(function (queryString) {
var requestUrl = getRequestUrl(queryString);
if (abortController) {
abortController.abort();
}
abortController = new AbortController();
fetch(requestUrl, {
signal: abortController.signal
}).then(function (res) {
return res.json();
}).then(function (response) {
abortController = undefined;
hugeList.innerHTML = '';
response.forEach(function (item) {
var listItem = document.createElement('option');
listItem.value = item;
hugeList.appendChild(listItem);
});
});
}, DELAY, value);
});
});