Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: perf debounce the search query #16586

Merged
merged 15 commits into from Nov 27, 2022
24 changes: 21 additions & 3 deletions docs/src/assets/js/search.js
Expand Up @@ -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
Expand All @@ -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();
Expand Down