From 48268770b758147e27371fab63f30a4c572e897b Mon Sep 17 00:00:00 2001 From: Alvie Rahman Date: Mon, 6 Feb 2023 13:42:45 +0000 Subject: [PATCH] add timer to search to reduce cpu usage --- search.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/search.js b/search.js index 7c5e73d..618b7dc 100644 --- a/search.js +++ b/search.js @@ -3,6 +3,9 @@ const PATH = "path" const TAGS = "tags" const TITLE = "title" +const SEARCH_TIMEOUT_MS = 100 +var SEARCH_TIMEOUT_ID = -1 + const fuse = new Fuse(data, { keys: [ { @@ -35,7 +38,14 @@ const resultsDiv = document.getElementById('results') var results = [] +function updateResultsWithTimeout() { + console.log("clearing timeout") + if (SEARCH_TIMEOUT_ID) SEARCH_TIMEOUT_ID = clearTimeout(SEARCH_TIMEOUT_ID) + SEARCH_TIMEOUT_ID = setTimeout(updateResults, SEARCH_TIMEOUT_MS) +} + function updateResults() { + console.log("updating results") resultsDiv.innerHTML = '' results = fuse.search(searchBar.value, { limit: RESULTS_MAX }) results.forEach(r => { @@ -99,10 +109,10 @@ searchBar.addEventListener('keyup', e => { } return } - updateResults() + updateResultsWithTimeout() }) -searchBar.addEventListener('change', updateResults) +searchBar.addEventListener('change', updateResultsWithTimeout) const searchParams = new URL(window.location.href).searchParams; searchBar.value = searchParams.get('q');