From ade621dd12fcd3b65644bb3468248cc040db756c Mon Sep 17 00:00:00 2001 From: Shanmughapriyan S Date: Sun, 27 Nov 2022 16:57:32 +0530 Subject: [PATCH] docs: perf debounce the search query (#16586) * perf: debounce search results * fix nits Co-authored-by: Amaresh S M * fix typo Co-authored-by: Amaresh S M * 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 * fix typo Co-authored-by: Amaresh S M * add apply * chore: update the debounce fn parameter * chore: update js doc commments * chore: add punctuation Co-authored-by: Amaresh S M --- docs/src/assets/js/search.js | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/src/assets/js/search.js b/docs/src/assets/js/search.js index 1de0f475eee..780e3dee107 100644 --- a/docs/src/assets/js/search.js +++ b/docs/src/assets/js/search.js @@ -111,6 +111,25 @@ function maintainScrollVisibility(activeElement, scrollParent) { } +/** + * Debounces the provided callback with a given delay. + * @param {Function} callback The callback that needs to be debounced. + * @param {Number} delay Time in ms that the timer should wait before the callback is executed. + * @returns {Function} Returns the new debounced function. + */ +function debounce(callback, delay) { + let timer; + return (...args) => { + if (timer) clearTimeout(timer); + timer = setTimeout(() => callback.apply(this, args), delay); + } +} + +const debouncedFetchSearchResults = debounce((query) => { + fetchSearchResults(query) + .then(displaySearchResults) + .catch(clearSearchResults); +}, 300); //----------------------------------------------------------------------------- // Event Handlers @@ -127,9 +146,8 @@ if(searchInput) else searchClearBtn.setAttribute('hidden', ''); if (query.length > 2) { - fetchSearchResults(query) - .then(displaySearchResults) - .catch(clearSearchResults); + + debouncedFetchSearchResults(query); document.addEventListener('click', function(e) { if(e.target !== resultsElement) clearSearchResults();