Skip to content

Commit

Permalink
Merge pull request #544 from samvera-labs/debounce-timer
Browse files Browse the repository at this point in the history
Use a debounce timer for content search request
  • Loading branch information
Dananji authored Jul 1, 2024
2 parents 2c55074 + 94633c3 commit 03edd24
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/services/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export function useFilteredTranscripts({
const [searchService, setSearchService] = useState();
const [allSearchResults, setAllSearchResults] = useState(null);
const abortControllerRef = useRef(null);
const debounceTimerRef = useRef(0);

const { matcher, itemsWithIds, itemsIndexed } = useMemo(() => {
const itemsWithIds = (transcripts || []).map((item, idx) => (
Expand Down Expand Up @@ -168,18 +169,23 @@ export function useFilteredTranscripts({
}, [matcher, query, enabled, sorter, matchesOnly, showMarkers, playerDispatch, selectedTranscript]);

const callSearchFactory = () => {
clearTimeout(debounceTimerRef.current);

const abortController = new AbortController();
abortControllerRef.current = abortController;

(Promise.resolve(matcher(query, abortControllerRef.current))
.then(({ matchedTranscriptLines, hitCounts, allSearchHits }) => {
if (abortController.signal.aborted) return;
markMatchedItems(matchedTranscriptLines, hitCounts, allSearchHits);
})
.catch(e => {
console.error('search failed', e, query, transcripts);
})
);
// Wait 5 milliseconds before submitting the search request, to avoid unnecessary UI updates
debounceTimerRef.current = setTimeout(() => {
(Promise.resolve(matcher(query, abortControllerRef.current))
.then(({ matchedTranscriptLines, hitCounts, allSearchHits }) => {
if (abortController.signal.aborted) return;
markMatchedItems(matchedTranscriptLines, hitCounts, allSearchHits);
})
.catch(e => {
console.error('search failed', e, query, transcripts);
})
);
}, 5);
};
/**
* Generic function to prepare a list of search hits to be displayed in the transcript
Expand Down

0 comments on commit 03edd24

Please sign in to comment.