Skip to content
Discussion options

You must be logged in to vote

For search/filter inputs, I would generally combine debouncing with AbortController.

1. Debounce user input

Instead of making a request on every keystroke, wait until the user stops typing for a short period.

let timer;

function search(query) {
  clearTimeout(timer);

  timer = setTimeout(() => {
    fetchResults(query);
  }, 300);
}


Code:-
let controller;

async function fetchResults(query) {
  controller?.abort();
  controller = new AbortController();

  try {
    const response = await fetch(
      `/api/search?q=${encodeURIComponent(query)}`,
      { signal: controller.signal }
    );

    const data = await response.json();
    updateUI(data);
  } catch (error) {
    if (error.name …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by 4kash7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants