Skip to content

Commit ade621d

Browse files
docs: perf debounce the search query (#16586)
* perf: debounce search results * fix nits Co-authored-by: Amaresh S M <amareshsm13@gmail.com> * fix typo Co-authored-by: Amaresh S M <amareshsm13@gmail.com> * add apply * chore: update the debounce fn parameter * chore: update js doc commments * chore: add punctuation * perf: debounce search results * fix nits Co-authored-by: Amaresh S M <amareshsm13@gmail.com> * fix typo Co-authored-by: Amaresh S M <amareshsm13@gmail.com> * add apply * chore: update the debounce fn parameter * chore: update js doc commments * chore: add punctuation Co-authored-by: Amaresh S M <amareshsm13@gmail.com>
1 parent a91332b commit ade621d

1 file changed

Lines changed: 21 additions & 3 deletions

File tree

docs/src/assets/js/search.js

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,25 @@ function maintainScrollVisibility(activeElement, scrollParent) {
111111

112112
}
113113

114+
/**
115+
* Debounces the provided callback with a given delay.
116+
* @param {Function} callback The callback that needs to be debounced.
117+
* @param {Number} delay Time in ms that the timer should wait before the callback is executed.
118+
* @returns {Function} Returns the new debounced function.
119+
*/
120+
function debounce(callback, delay) {
121+
let timer;
122+
return (...args) => {
123+
if (timer) clearTimeout(timer);
124+
timer = setTimeout(() => callback.apply(this, args), delay);
125+
}
126+
}
127+
128+
const debouncedFetchSearchResults = debounce((query) => {
129+
fetchSearchResults(query)
130+
.then(displaySearchResults)
131+
.catch(clearSearchResults);
132+
}, 300);
114133

115134
//-----------------------------------------------------------------------------
116135
// Event Handlers
@@ -127,9 +146,8 @@ if(searchInput)
127146
else searchClearBtn.setAttribute('hidden', '');
128147

129148
if (query.length > 2) {
130-
fetchSearchResults(query)
131-
.then(displaySearchResults)
132-
.catch(clearSearchResults);
149+
150+
debouncedFetchSearchResults(query);
133151

134152
document.addEventListener('click', function(e) {
135153
if(e.target !== resultsElement) clearSearchResults();

0 commit comments

Comments
 (0)