Debounce vs. Throttle in JavaScript: How to Control Events That Fire Too Often

Learn what debounce and throttle do in JavaScript, how to write each one, and when to use them for search boxes, scrolling and resizing.

Share on Linkedin Share on WhatsApp

Estimated reading time: 7 minutes

Article image Debounce vs. Throttle in JavaScript: How to Control Events That Fire Too Often

Some browser events fire far more often than you might expect. Scrolling a page can trigger dozens of scroll events per second. Typing a single word in a search box fires an input event for every keystroke. Resizing a window produces a steady stream of resize events. If each event runs an expensive task, such as calling an API or recalculating a layout, your page can become slow and wasteful. Two classic techniques solve this problem: debounce and throttle. In this article, you will learn what each one does, how to write them in plain JavaScript, and how to choose the right one.

The problem: too many function calls

Consider a search field that suggests results as the user types. A naive implementation sends a request on every keystroke:

searchInput.addEventListener('input', (event) => {
  fetchSuggestions(event.target.value);
});

If someone types “javascript,” that is ten requests, and most of them are useless because the user has not finished typing. The server does extra work, the network is busier than it needs to be, and responses may even arrive out of order. Debounce and throttle both reduce how often a function runs, but they do it in different ways.

What is debounce?

Debouncing delays a function until a certain amount of time has passed without the event firing again. Every new event resets the timer. The function only runs once the activity stops.

A helpful analogy is an elevator door. Each time someone walks in, the door waits a little longer before closing. It only closes when nobody has entered for a few seconds.

Here is a simple debounce function:

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

And here is how you would use it in the search example:

const debouncedFetch = debounce((value) => {
  fetchSuggestions(value);
}, 300);

searchInput.addEventListener('input', (event) => {
  debouncedFetch(event.target.value);
});

Now the request is only sent when the user pauses typing for 300 milliseconds. A fast typist who enters a whole word in one burst triggers a single request instead of many.

What is throttle?

Throttling guarantees that a function runs at most once in a given time interval, no matter how many times the event fires. Unlike debounce, it keeps running regularly while the activity continues.

Think of a security guard who lets one person through a gate every two seconds. People can keep arriving, but the flow is limited to a steady rate.

A basic throttle function looks like this:

function throttle(fn, interval) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= interval) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

A typical use is tracking scroll position, for example to show a “back to top” button or update a reading progress bar:

const onScroll = throttle(() => {
  updateProgressBar(window.scrollY);
}, 100);

window.addEventListener('scroll', onScroll);

The progress bar updates up to ten times per second while the user scrolls, which feels smooth without running the code on every single event.

Note that this simple version runs the function immediately on the first event and then ignores calls until the interval passes. That means the very last event may be skipped. More complete implementations add a final “trailing” call so the end state is always captured.

Debounce vs. throttle at a glance

AspectDebounceThrottle
When the function runsAfter the events stop for a set timeAt regular intervals while events continue
During continuous activityDoes not run until activity endsRuns periodically
Best forReacting to the final valueReacting steadily during activity
Common examplesSearch suggestions, form validation, auto-saving draftsScroll tracking, infinite scroll checks, mouse movement, game input

How to choose the right technique

A simple question usually settles it: do you care about the final result or about regular updates along the way?

  • Choose debounce when only the end of the activity matters. Validating an email field after the user stops typing, saving a draft after a pause, or recalculating a layout once the window has finished resizing are good examples.
  • Choose throttle when the user expects continuous feedback. Updating the position of an element while dragging, checking whether the user has scrolled near the bottom of a list, or limiting how fast a button can trigger an action all benefit from throttling.

Choosing a good delay

There is no single correct value. For typing, delays between roughly 200 and 500 milliseconds are common: short enough to feel responsive, long enough to skip most keystrokes. For scroll and mouse events, intervals around 100 milliseconds or less usually feel smooth. The best approach is to test with real users and adjust. A delay that is too long makes the interface feel sluggish; one that is too short brings back the original performance problem.

Practical tips

  • Create the wrapped function once. Calling debounce() inside the event handler creates a new timer every time and breaks the behavior. Wrap the function outside the listener, as in the examples above.
  • Consider existing utilities. Libraries such as Lodash provide well-tested debounce and throttle functions with extra options, like leading and trailing calls and cancellation.
  • Clean up in components. In frameworks such as React or Vue, cancel pending timers when a component is removed to avoid running code on elements that no longer exist.
  • Look for native alternatives. For visual updates tied to animation, requestAnimationFrame can be a better fit. To detect when elements enter the screen, the IntersectionObserver API often replaces throttled scroll listeners entirely.

Conclusion

Debounce and throttle are small functions with a big impact on performance and user experience. Debounce waits for the activity to stop and then acts once; throttle acts at a steady pace while the activity continues. Knowing the difference helps you build interfaces that feel fast, use fewer resources, and put less load on your servers.

If you want to keep building your front-end skills, check out the free Web Development courses on Cursa and practice these techniques in your own projects.

Video Courses

Free video courses

See all video courses

NTFS, exFAT, FAT32 and APFS: Choosing the Right File System for a Drive

Understand what a file system does and how NTFS, exFAT, FAT32, APFS and ext4 differ, so you can format drives without losing compatibility.

Text Encoding Explained: ASCII, Unicode and Why You Sometimes See Strange Symbols

Learn how computers store text, what ASCII and Unicode actually are, why UTF-8 became the standard, and how to fix files that display garbled characters.

Idempotency in APIs: Why Retrying a Request Should Be Safe

Learn what idempotency means in backend development, which HTTP methods provide it, and how idempotency keys prevent duplicate operations.

What Is a CDN? How Content Delivery Networks Make Websites Fast

Learn what a CDN is, how edge caching and cache headers work, what a cache hit means, and when a CDN helps — or does not.

Semantic Versioning Explained: What a Number Like 2.4.1 Actually Tells You

MAJOR.MINOR.PATCH is a promise, not decoration. Learn to read version numbers and understand dependency range symbols.

What Is a Virtual Machine? Virtualization Explained for Beginners

Learn what a virtual machine is, how hypervisors work, how VMs differ from containers, and when to use each one.

How HTTPS Works: Certificates, the TLS Handshake and What the Padlock Really Means

A beginner-friendly walkthrough of HTTPS: what TLS certificates prove, how the handshake works, and what the browser padlock does not guarantee.

Big O Notation Explained: How to Talk About Code Efficiency

A beginner-friendly guide to Big O notation: what it measures, the most common complexity classes, and how to reason about the cost of your code.