Sobes.tech
Middle+

How did you optimize backend queries? What is debounce and throttle, and how do they differ?

sobes.tech AI

Answer from AI

Query optimization for the backend often involves reducing the number of requests and controlling their frequency. For example, when entering text into a search bar, techniques like debounce and throttle can be used.

Debounce delays the execution of a function until a certain period of time has passed without any events. This means the request will only be sent after the user stops typing, for example, 300 ms after the last keystroke.

Throttle limits the execution of a function, allowing it to be called no more often than a specified interval. For example, if throttle is set to 500 ms, the function will be called at most once every 500 ms, even if events occur more frequently.

Difference:

  • Debounce postpones the call until the end of a series of events.
  • Throttle guarantees the function is called at a certain frequency during a series of events.

Example of debounce in JavaScript:

function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

const fetchSuggestions = debounce((query) => {
  fetch(`/api/search?q=${query}`)
    .then(res => res.json())
    .then(data => console.log(data));
}, 300);

inputElement.addEventListener('input', (e) => {
  fetchSuggestions(e.target.value);
});
How did you optimize backend queries? What is… - sobes.tech