WebTech1223411 logo WebTech1223411Web tech, read closely
Front-End

Debounce vs Throttle in JavaScript and When to Use Each

Your search box fires an API request on every keystroke, so typing "headphones" sends ten requests and the results flicker as responses arrive out of order.

A developer's monitor showing a search box with typed text and a timeline of keystroke events below it, a coffee mug and sticky notes with millisecond values beside the keyboard

Your search box fires an API request on every keystroke, so typing "headphones" sends ten requests and the results flicker as responses arrive out of order. Or your scroll handler runs 120 times a second and the page stutters on a mid range phone. Both problems have the same family of fixes, and picking between debounce vs throttle is the part people most often get backwards.

This article explains what each technique does, when to use which, how to write them without a library, and the cases where neither is the right answer.

Debounce vs throttle in one sentence each

Debounce waits until events stop for a set time, then runs the function once. If another event arrives during the wait, the timer resets.

Throttle runs the function at most once per set interval, no matter how many events arrive in between.

Picture someone typing "laptop" with 100 milliseconds between keys. With a 300 ms debounce, nothing runs while they type, and the handler fires once, 300 ms after the final "p." With a 300 ms throttle, the handler fires on the first key, again around the fourth key, and then possibly once more at the end. Debounce cares about the pause. Throttle cares about the pace.

When to use each one

SituationBetter choiceTypical delay
Search as you typeDebounce250 to 400 ms
Form field validationDebounce400 to 600 ms
Auto saving a draftDebounce1 to 2 seconds
Window resize recalculationDebounce150 to 250 ms
Scroll position for a progress barThrottleEvery animation frame
Infinite scroll triggerThrottle200 to 300 ms
Pointer move for drag previewsThrottleEvery animation frame
Analytics for user activityThrottle1 to 5 seconds

The rule of thumb: if the user only cares about the final value, debounce. If the user needs to see continuous feedback while the action happens, throttle.

Writing debounce without a library

A basic debounce is about eight lines. Here is the logic, step by step:

  1. Create a function called debounce that takes your callback and a delay in milliseconds.
  2. Inside it, declare a variable to hold a timer ID.
  3. Return a new function that accepts any arguments.
  4. Each time the new function is called, run clearTimeout on the stored timer ID.
  5. Then call setTimeout with your callback and the delay, passing the latest arguments, and store the new ID.

Because every call cancels the previous timer, the callback only survives once calls stop for the full delay. Attach the returned function as your input listener, not the original callback.

Two improvements are worth adding. First, a cancel method that clears the timer, so a component that unmounts does not run a stale callback. Second, for search, combine debounce with an AbortController so that if a slow response from "lap" arrives after the response for "laptop," you can abort the old request rather than show the wrong results.

Writing throttle without a library

The simplest throttle tracks time:

  1. Create a throttle function that takes a callback and an interval.
  2. Store the timestamp of the last run, starting at zero.
  3. In the returned function, read the current time with performance.now().
  4. If the difference since the last run is at least the interval, run the callback and update the stored timestamp. Otherwise, do nothing.

This version drops the final event if it lands inside the interval, which can leave a progress bar stuck at 97 percent. A "trailing" throttle fixes that by scheduling one last call with setTimeout for the remaining time.

For anything visual, a cleaner option is to throttle to the frame rate with requestAnimationFrame. Set a flag when an event arrives, schedule one frame callback if none is pending, and do the work inside it. You never run more than once per frame, and the browser pauses the work in background tabs. To see why this timing matters, our explainer on how the browser event loop decides when your code runs walks through tasks and frames.

Why you often need neither

Many tutorials treat throttling scroll handlers as standard practice. In modern browsers, that advice is often out of date, and adding throttle can hide the real issue.

A lot of classic scroll handlers exist to detect when something enters the viewport: lazy loading images, starting an animation, loading the next page of results. IntersectionObserver does that natively, runs off the main thread where it can, and needs no throttle at all. Similarly, ResizeObserver reports element size changes far more precisely than throttling a window resize event.

Some effects need no JavaScript. Sticky headers, scroll snapping and even scroll linked progress bars can now be done in CSS in current browsers, which is smoother than any throttled handler.

And if your handler is slow because it reads layout and then writes styles in a loop, throttling only makes the jank less frequent. The fix is to stop forcing layout. Our guide to how reflow and repaint slow down your page shows how to spot that pattern.

Common mistakes to watch for

  • Creating a new debounced function on every render. In component frameworks, wrapping the handler inline creates a fresh timer each render, so nothing is ever debounced. Create it once and keep a stable reference.
  • Debouncing a button click for "double click protection." It delays the action, which feels broken. Disable the button while the request is in flight instead.
  • Delays that are too long. A 1 second debounce on search makes the interface feel slow. Users notice delays above roughly 400 ms.
  • Forgetting the leading edge. A plain debounce waits before the first run, which feels laggy for actions like opening a menu. A "leading" option runs immediately on the first event, then ignores the rest until the pause ends.
  • Losing "this" and arguments. Pass the arguments through, and use arrow functions or apply so the callback keeps its context.

When debugging timing, logging with timestamps helps. The tips in console methods beyond console.log make it easy to time each call.

Frequently asked questions

What is the difference between debounce and throttle?

Debounce runs a function once after events have stopped for a set delay. Throttle runs it at regular intervals while events keep coming. Use debounce when only the final value matters and throttle when you need steady updates during the action.

Should I debounce or throttle a scroll event?

Usually throttle, ideally to the animation frame, because the user expects continuous feedback while scrolling. Before doing either, check whether IntersectionObserver or a CSS feature can replace the scroll handler entirely, since that is often faster and simpler.

What is a good debounce time for a search input?

Between 250 and 400 milliseconds works for most search boxes. Shorter delays send more requests, and longer delays make the interface feel sluggish. Pair the debounce with request cancellation so outdated responses never replace newer results.

LV
Lorenzo Vidal

Lorenzo started as a visual designer and moved into CSS after watching too many of his layouts fall apart on phones. He writes about front-end craft, interfaces and accessibility, and still tests everything with the keyboard first.

More posts by Lorenzo

More in Front-End

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto