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 @@ -114,6 +114,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 shoud wait before the callback is executed.
shanpriyan marked this conversation as resolved.
Show resolved Hide resolved
* @returns {Function}
*/
function debounce(callback, delay) {
let timer;
return (...args) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => callback(...args), delay)
shanpriyan marked this conversation as resolved.
Show resolved Hide resolved
}
}

const debouncedFetchSearchResults = debounce((query, onsuccess, onerror) => {
fetchSearchResults(query)
.then(onsuccess)
.catch(onerror);
}, 300);
shanpriyan marked this conversation as resolved.
Show resolved Hide resolved

//-----------------------------------------------------------------------------
// Event Handlers
Expand All @@ -130,9 +149,8 @@ if(searchInput)
else searchClearBtn.setAttribute('hidden', '');

if (query.length > 2) {
fetchSearchResults(query)
.then(displaySearchResults)
.catch(clearSearchResults);

debouncedFetchSearchResults(query, displaySearchResults, clearSearchResults);

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