Suggest an editImprove this articleRefine the answer for “When should you use debounce?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Debounce** is used when you need to **run an action only after a stream of frequent events has stopped**: the function fires once, X ms after the last event. It is the opposite of throttle (which runs at a regular interval). **Key point:** debounce is needed when it matters to run an action *after the user has stopped doing something* - for example, live search, form draft autosave, or form validation.Shown above the full answer for quick recall.Answer (EN)Image**Debounce** is used when you need to **run an action only after a stream of frequent events has stopped**. That is, the function fires **once, X ms after the last event**. In simple terms: > **Debounce is needed when it matters to run an action** ***after the user has stopped doing something*****.** It is the opposite of throttle (which runs at a regular interval). --- ## When should you use debounce? Below are the most common and most correct examples expected in an interview. --- ## 1. Search as you type (live search) The user types fast → there is no need to send a request to the server for every character. **We use debounce** to send the request only after the user has stopped typing: ```js watch(searchInput, debounce((value) => { fetchData(value) }, 300)) ``` --- ## 2. Autocomplete / suggestions in forms Also done after a pause, otherwise there are too many API requests. --- ## 3. Validating a form "once typing is done" There's no point checking an email on every character. Debounce avoids unnecessary computation and unnecessary UI logic. --- ## 4. Saving form drafts (autosave) If you save on every input → the server gets overloaded. The correct approach: save the draft 500-1000 ms after the last change. --- ## 5. Reacting to window resize, but *once* after the change is done If you need to recalculate the layout ONLY once the user has finished resizing the window: ```js window.addEventListener('resize', debounce(updateLayout, 300)) ``` --- ## Important: the difference from throttle (a common question) | Approach | When it fires | |---|---| | **Debounce** | *After the stream of events has stopped* | | **Throttle** | *Regularly, but no more often than the given interval* | **Example:** - Debounce: run a search once the user has stopped typing. - Throttle: update the scroll position every 100 ms. --- ## debounce example (lodash) ```js import debounce from 'lodash/debounce' const handleInput = debounce((value) => { console.log(value) }, 300) ``` --- ## A simple debounce built by hand ```js function debounce(fn, delay) { let timeout return function (...args) { clearTimeout(timeout) timeout = setTimeout(() => { fn.apply(this, args) }, delay) } } ```For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.