diff --git a/README.md b/README.md index a83e3a4..b39cae7 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # wikipedia-search-engine -hello there, your task is to use debounce technique with the search input on the top of the page. +Problem: +The search input on the top of the page lacks debounce technique, which means that every keystroke triggers a search request. This can cause unnecessary server load and slow down the search functionality, especially when the user types quickly or makes a typo. -fork the repository and start working on it. - -best of luck. +Solution: +To solve this problem, I need to implement debounce technique for the search input. This will delay the search request until the user stops typing for a certain amount of time \ No newline at end of file diff --git a/script.js b/script.js index 9ff78b9..0a711a1 100644 --- a/script.js +++ b/script.js @@ -1,37 +1,45 @@ -let resultsContainer = document.getElementsByClassName("container")[0] +let resultsContainer = document.getElementsByClassName("container")[0]; +let debounceTimer; + +const debounce = (func, delay) => { + clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => func(), delay); +}; const validateInput = (el) => { - if(el.value === ""){ - resultsContainer.innerHTML = "
Type something in the above search input
" - }else{ - generateResults(el.value, el) + debounce(() => { + if (el.value === "") { + resultsContainer.innerHTML = "Type something in the above search input
"; + } else { + generateResults(el.value, el); } -} + }, 500); +}; 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
"; + } + }); +};