diff --git a/script.js b/script.js index 9ff78b9..c7eff04 100644 --- a/script.js +++ b/script.js @@ -1,37 +1,55 @@ -let resultsContainer = document.getElementsByClassName("container")[0] +let resultsContainer = document.querySelector(".container"); +let input = document.querySelector("input"); + +let updateDb = debounce((Text) => { + generateResults(Text); +}); const validateInput = (el) => { - if(el.value === ""){ - resultsContainer.innerHTML = "
Type something in the above search input
" - }else{ - generateResults(el.value, el) - } -} + if (el.value === "") { + resultsContainer.innerHTML = + "Type something in the above search input
"; + } else { + updateDb(el.value); + } +}; -const generateResults = (searchValue, inputField) => { - fetch( - "https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=" - + searchValue - ) - .then(response => response.json()) - .then(data => { - let results = data.query.search - let numberOfResults = data.query.search.length - resultsContainer.innerHTML = "" - for(let i=0; i${results[i].snippet}
Type something in the above search input
" - } - }) -} \ No newline at end of file + `; + resultsContainer.appendChild(result); + } + if (inputField.value === "") { + resultsContainer.innerHTML = + "Type something in the above search input
"; + } + }); +}; + +function debounce(callback, dealy = 500) { + let timeout; + return (...args) => { + clearTimeout(timeout); + timeout = setTimeout(() => { + callback(...args); + }, dealy); + }; +}