MediumAsync in React💻 Output Question

Debounced search — only fires after typing stops

💡

Hint

Debouncing in React: useEffect with a setTimeout + cleanup. The cleanup clears the pending timeout when the value changes, so only the final value triggers the actual search.

What does this output?

function debounce(fn, delay) {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const searchLog = [];
let searchCallCount = 0;

const search = debounce((query) => {
  searchCallCount++;
  searchLog.push('search:' + query);
}, 50);

// Simulate fast typing
['r', 're', 'rea', 'reac', 'react'].forEach((q, i) => {
  setTimeout(() => search(q), i * 10); // 10ms apart, debounce is 50ms
});

// After all typing stops (5 * 10 = 50ms) + 50ms debounce = 100ms
setTimeout(() => {
  console.log(searchCallCount);
  console.log(searchLog[0]);
}, 150);

Correct Output

1
search:react

Why this output?

Explanation: Each keystroke resets the 50ms timer. Only the last keystroke ('react' at 40ms) fires — its timer completes at 90ms with no further input.

Key Insight: Debouncing in React: useEffect with a setTimeout + cleanup. The cleanup clears the pending timeout when the value changes, so only the final value triggers the actual search.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz