A request on every keystroke: when should a search box debounce or throttle?

April 21, 2025

If a search box calls fetch on every input event, quickly typing cat sends queries for c, ca, and cat. By the time the first suggestions come back, the user may have finished typing. This calls for debouncing: restart the timer on every input, then search for the current term when the user pauses. A “Refresh scores” button has a different requirement. The first click is worth an immediate request, and subsequent rapid clicks can be skipped. This calls for throttling, with a minimum interval between refreshes.1

With the same 300 ms interval, how many calls actually run?

Suppose the user triggers an event at 0, 100, 200, and 350 milliseconds, then stops. The table uses two common implementations and assumes timers can run exactly when they expire.

HandlingWhen the application function runsWhat happens at 350 ms
Run on every event0, 100, 200, 350 msThe fourth event triggers the fourth call
Debounce, run after a pause650 msCancel the call scheduled for 500 ms and start a new 300 ms wait at 350 ms
Throttle, run immediately when eligible0, 350 msMore than 300 ms have passed since the previous call, so this event can run immediately

The throttled function is eligible again at 300 ms, but there’s no new event then, so there’s no call. To choose between the two, ask: If the user keeps going, does the interface need to give feedback along the way? Both a reading progress bar and a saved reading position listen to scrolling. The progress bar needs updates during scrolling, a good fit for throttling. To remember only where the user stopped, debounce the save until after scrolling ends.2

How can autocomplete wait until the user pauses?

Setting a 300 ms timer on each input merely delays every request by 300 ms. To combine requests, the next input must be able to cancel the previous timer. The code below keeps the timer in the returned function’s closure, allowing each search box to have its own countdown.

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

Suppose the page has an input called #query, an element called #suggestions, and a search API returning an array of strings. Create scheduleSearch only once, before registering the listener, so successive inputs share the same timer.

const input = document.querySelector('#query')
const suggestions = document.querySelector('#suggestions')
let revision = 0

const scheduleSearch = debounce(async (query, version) => {
  if (!query) return
  try {
    const response = await fetch('/api/search?q=' + encodeURIComponent(query))
    if (!response.ok) throw new Error('搜索失败')
    const words = await response.json()
    if (version === revision) suggestions.textContent = words.join('、')
  } catch {
    if (version === revision) suggestions.textContent = '搜索失败,请重试'
  }
}, 300)

input.addEventListener('input', () => {
  revision += 1
  const query = input.value.trim()
  if (!query) suggestions.textContent = ''
  scheduleSearch(query, revision)
})

Why also track an input revision? Suppose the user types ca, pauses until its request goes out, and then adds t. Clearing the timer is now too late to stop the response for ca. Increment the revision on every input and the old response will skip the page update, even if it arrives before the next request goes out. Clearing the search field also invalidates the old response.

How can the refresh button respond on the first click?

Suppose the page already has a refreshScores function to fetch the latest scores. Attach the handler below to the button. The first click refreshes immediately. After that, a click counts only if at least a second has elapsed since the last refresh. Skipped clicks do not extend the wait.

function throttle(fn, interval) {
  let nextAllowed = -Infinity
  return (...args) => {
    const now = performance.now()
    if (now < nextAllowed) return
    nextAllowed = now + interval
    fn(...args)
  }
}

const refreshButton = document.querySelector('#refresh')
refreshButton.addEventListener('click', throttle(refreshScores, 1000))

This immediate-at-the-start approach is called leading. It suits a refresh button: if someone clicks three times in quick succession, another automatic refresh a second later is usually unnecessary. For a scroll progress bar, the final scroll event might be skipped and leave the bar at 98%. A throttle implementation with a trailing call can also show the final change that occurred during the waiting period.2

Finally, consider how long the request takes. If you throttle to one second and the API takes two seconds to respond, a second request can still overlap the first. If the button should accept a click only after the last request completes, disable it as the request starts and restore it in finally. The time the user can click again then depends on when the request ends.

Does event delegation replace throttling or debouncing?

Here is a common interview question: a <ul> can gain new <li> elements at any time. How can every item open its details when clicked? Attach a single click listener to the <ul>. When someone clicks an icon inside a list item, the event travels up through its ancestors. This is event bubbling. The list’s listener can call event.target.closest('li') to walk up from the icon and find the row to expand. Letting an ancestor handle its descendants’ events is called event delegation, and newly added rows will also respond to clicks.3

If the user clicks three times, the delegated listener still receives three clicks. Expanding a detail view warrants an immediate response. Whether to debounce or throttle a delegated handler depends on which results you can combine during a series of actions.

  • Each row searches for its own product. One input listener on the form can locate the search field via event.target, then call that field’s own debounced function. Suppose someone types “pencil” in the first row and “eraser” in the second row 100 ms later. With one shared 300 ms timer, “eraser” cancels the “pencil” query and the first row never gets suggestions. A separate timer per field lets both rows receive results. If the two fields actually filter the same results list, they can share a timer and search together using the latest values after the user pauses.
  • Dragging a node on a canvas. One pointermove listener on the canvas can handle the events. Move the node with the pointer and throttle only the network requests that send its coordinates. Send the final coordinates on release so the last bit of movement is recorded even if it falls within the throttle interval.

References

Footnotes

  1. Mato, M. [@otamnitram]. (2020, April 3). Throttling and Debouncing. Avoiding unnecessary API calls. [Blog post]. DEV Community. “When to use each one?” ↩

  2. MDN contributors. (2025, July 11). Debounce. MDN Web Docs. See also the same glossary’s discussion of scroll events and when throttling fires. ↩ ↩2

  3. MDN contributors. (2026, October 6). Event bubbling. MDN Web Docs. “Event delegation”. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-04-21). A request on every keystroke: when should a search box debounce or throttle?. https://caiborui.com/blog/2025-04-21-zh-frontend-debounce-throttle-entrans

@misc{borui2025-db2e318b,
  author = {borui},
  title = {{A request on every keystroke: when should a search box debounce or throttle?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-04-21-zh-frontend-debounce-throttle-entrans}
}