JavaScript

Debouncing and Throttling in JavaScript: A Practical Guide

Have you ever built a search box where the API gets called every time someone types a character? Or added a scroll event listener that makes your website feel…

D
DevByteTechnical Author
Published
16 min read4 views
Debouncing and Throttling in JavaScript: A Practical Guide

Have you ever built a search box where the API gets called every time someone types a character? Or added a scroll event listener that makes your website feel slow when users move down the page?

These problems are more common than they seem.

Imagine a user searching for a product by typing laptop. The browser fires an input event for every character. Without any optimization, your application might send five separate API requests:

l → API request
la → API request
lap → API request
lapt → API request
lapto → API request
laptop → API request

Most of those requests are unnecessary. The user hasn't finished typing, and the application is already doing work that might not be needed.

A similar problem happens with scroll and resize events. These events can fire many times in a short period, potentially causing expensive calculations, repeated DOM updates, or unnecessary API calls.

This is where debouncing and throttling become useful.

Both techniques help control how frequently a function executes. However, they solve slightly different problems. Debouncing waits for activity to stop, while throttling limits how often a function can run during continuous activity.

In this guide, we'll understand both concepts from scratch, implement them in JavaScript, explore practical use cases, and see how to use them in React applications.

1. What Is Debouncing in JavaScript?

Debouncing is a technique that delays the execution of a function until a specified amount of time has passed without another triggering event.

Whenever a new event occurs, the timer resets.

The function executes only when the events stop arriving for the configured duration.

Let's understand this with a search input.

Suppose you want to search a product catalog when a user types something. You could wait for 500 milliseconds after the user's last keystroke before sending the request.

If the user types continuously, the timer keeps resetting.

User types:  l  a  p  t  o  p
             ↓  ↓  ↓  ↓  ↓  ↓
Timer:       reset on every keystroke
             ↓
500ms without input
             ↓
Search API executes once

Instead of sending a request for every character, the application sends one request after the user pauses.

A simple example

Let's start with a regular JavaScript function:

function searchProducts(query) {
  console.log("Searching for:", query);
}

If we call it on every input event, it executes immediately:

const searchInput = document.querySelector("#search");

searchInput.addEventListener("input", (event) => {
  searchProducts(event.target.value);
});

This works, but it can trigger too many searches.

Let's improve it using debouncing.

Implementing debouncing from scratch

function debounce(callback, delay) {
  let timer;

  return function (...args) {
    clearTimeout(timer);

    timer = setTimeout(() => {
      callback.apply(this, args);
    }, delay);
  };
}

At first glance, this function might look complicated, but the idea is straightforward.

Let's break it down.

Step 1: Store a timer

let timer;

The timer variable keeps track of the pending execution.

Because it belongs to the outer function, the returned function can access it even after debounce() has finished running. This is an example of a JavaScript closure.

Step 2: Clear the previous timer

clearTimeout(timer);

Whenever the returned function is called again, the previous timer is cancelled.

This prevents the earlier scheduled callback from executing.

Step 3: Schedule a new execution

timer = setTimeout(() => {
  callback.apply(this, args);
}, delay);

A new timer is created. If no new event arrives before the delay expires, the callback executes.

The ...args syntax preserves the arguments passed to the debounced function. Using apply() also preserves the calling context represented by this.

Now let's use our debounce function.

const searchInput = document.querySelector("#search");

const debouncedSearch = debounce((query) => {
  console.log("Searching for:", query);
}, 500);

searchInput.addEventListener("input", (event) => {
  debouncedSearch(event.target.value);
});

Now the search function executes only after the user stops typing for approximately 500 milliseconds.

This is a basic trailing-edge debounce implementation. It doesn't execute immediately on the first event; it waits for the activity to pause.

2. Building a Real Search Example with Debouncing

Let's take the previous example one step further.

Suppose your backend exposes an API endpoint:

GET /api/products?search=laptop

You want to fetch matching products whenever the user searches.

Here's a practical implementation:

async function searchProducts(query) {
  if (!query.trim()) {
    console.log("Please enter a search term");
    return;
  }

  try {
    const response = await fetch(
      `/api/products?search=${encodeURIComponent(query)}`
    );

    if (!response.ok) {
      throw new Error("Failed to fetch products");
    }

    const products = await response.json();

    console.log("Products:", products);
  } catch (error) {
    console.error("Search failed:", error);
  }
}

Now connect it to the debounced function:

const searchInput = document.querySelector("#search");

const debouncedSearch = debounce(searchProducts, 500);

searchInput.addEventListener("input", (event) => {
  debouncedSearch(event.target.value);
});

The flow is now simple:

  1. The user types into the search box.

  2. The input event triggers the debounced function.

  3. The previous timer is cancelled.

  4. A new 500-millisecond timer starts.

  5. If the user types again, the timer resets.

  6. Once the user pauses, the API request begins.

This reduces unnecessary requests and can make search interfaces feel more responsive.

However, debouncing doesn't automatically cancel an API request that has already started. If users change their search quickly, earlier requests can still finish after later ones.

For a production search interface, consider using AbortController to cancel outdated requests or checking request IDs before updating the UI.

We'll revisit this when discussing common mistakes.

3. What Is Throttling in JavaScript?

Throttling is another technique for controlling function execution, but it behaves differently from debouncing.

Throttling limits how frequently a function can execute during continuous activity.

Instead of waiting for the activity to stop, a throttled function can execute at controlled intervals while the activity continues.

For example, imagine a user scrolling through a long webpage.

The browser may fire many scroll events in a short period. If you run an expensive function for every event, you may waste CPU time.

With throttling, you can limit that function to execute at most once every 200 milliseconds.

Scroll events:  ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
                ↓
Throttled work: ✓       ✓       ✓
                Every 200ms

The exact execution pattern depends on the throttle implementation. Some implementations execute immediately on the first event, while others delay the first execution.

The important point is that the function doesn't execute for every event.

Implementing throttling from scratch

Let's implement a simple leading-edge throttle.

function throttle(callback, delay) {
  let lastExecution = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastExecution >= delay) {
      lastExecution = now;

      callback.apply(this, args);
    }
  };
}

This implementation uses the current timestamp to determine whether enough time has passed since the previous execution.

Let's understand it.

Step 1: Store the last execution time

let lastExecution = 0;

This variable records when the callback last ran.

Step 2: Get the current time

const now = Date.now();

Date.now() returns the current timestamp in milliseconds.

Step 3: Check the elapsed time

if (now - lastExecution >= delay) {

If the elapsed time is greater than or equal to the configured delay, the function can execute.

Step 4: Update the timestamp

lastExecution = now;

callback.apply(this, args);

After execution, the timestamp is updated. Subsequent events are ignored until the interval has passed.

This is a basic throttle implementation. Events that arrive during the blocked interval are discarded rather than queued for a later execution.

Using throttling with scroll events

Suppose you want to track the user's scroll position.

function handleScroll() {
  console.log("Scroll position:", window.scrollY);
}

const throttledScroll = throttle(handleScroll, 200);

window.addEventListener("scroll", throttledScroll);

The browser can continue firing scroll events, but handleScroll() runs at most once per configured interval.

This can be useful when the handler performs work that doesn't need to run for every individual scroll event.

Examples include:

  • Updating noncritical scroll indicators.

  • Tracking scroll activity for analytics.

  • Performing periodic calculations based on the current scroll position.

  • Updating certain UI elements in response to scrolling.

However, throttling doesn't make an expensive operation automatically cheap. If the callback takes too long to execute, it can still cause performance problems.

For visual updates tied to rendering, requestAnimationFrame() may be a better choice.

4. Debouncing vs. Throttling: What's the Difference?

Both techniques reduce how frequently a function executes, but they serve different purposes.

Feature

Debouncing

Throttling

Main purpose

Wait until activity pauses

Limit execution frequency

Execution behavior

Runs after a quiet period

Can run at controlled intervals

Timer behavior

Resets after each event

Controls when another execution is allowed

Continuous activity

May not execute until activity stops

Can execute while activity continues

Search input

Excellent for reducing unnecessary searches

Useful in specific continuous-search scenarios

Scroll events

Useful when work is needed after scrolling stops

Useful for periodic processing

Window resize

Useful for recalculating after resizing finishes

Useful for controlled updates during resizing

Typical use case

Search suggestions, form validation

Scroll tracking, rate-limited event handling

Here's the easiest way to remember the difference:

Debouncing: "Wait until the user stops doing something."

Throttling: "Don't do this more often than the configured interval."

Neither technique is universally better. The right choice depends on when you need the callback to execute.

5. Understanding Debouncing with Window Resize Events

Another common use case is the browser's resize event.

Consider a dashboard with multiple charts. When the browser window changes size, the application may need to recalculate chart dimensions.

A simple implementation might look like this:

window.addEventListener("resize", () => {
  recalculateDashboardLayout();
});

The problem is that resize events can fire repeatedly while the user drags the window's edge.

If recalculateDashboardLayout() is expensive, repeated execution may affect performance.

Debouncing can help:

const debouncedResize = debounce(() => {
  recalculateDashboardLayout();

  console.log("Dashboard layout recalculated");
}, 300);

window.addEventListener("resize", debouncedResize);

Now the recalculation runs after the resize events have stopped arriving for approximately 300 milliseconds.

This is useful when the final dimensions matter more than intermediate dimensions.

However, if the dashboard must respond continuously during resizing, a throttled approach or a ResizeObserver may be more appropriate.

For individual elements, ResizeObserver is often a better fit than monitoring the entire window because it reports changes to the dimensions of specific elements.

6. Implementing Debouncing in React

If you're working with React, you can apply the same concept to search inputs, filters, and API calls.

Let's build a simple component.

import { useEffect, useState } from "react";

function SearchProducts() {
  const [query, setQuery] = useState("");
  const [debouncedQuery, setDebouncedQuery] = useState("");

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(query);
    }, 500);

    return () => {
      clearTimeout(timer);
    };
  }, [query]);

  useEffect(() => {
    if (!debouncedQuery.trim()) {
      return;
    }

    console.log("Search API called:", debouncedQuery);

    // Fetch matching products here.
  }, [debouncedQuery]);

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        placeholder="Search products..."
      />

      <p>Current input: {query}</p>
      <p>Debounced input: {debouncedQuery}</p>
    </div>
  );
}

export default SearchProducts;

This component uses React state and effects to implement debouncing.

How does it work?

The first effect runs whenever query changes.

It schedules an update to debouncedQuery after 500 milliseconds.

If another keystroke changes query before the timer finishes, React runs the effect's cleanup function and cancels the previous timer.

A new timer is then scheduled.

The second effect runs when debouncedQuery changes. That's where you can perform the search request.

This approach keeps the debouncing logic close to the component and is often enough for a straightforward search field.

Important: Debouncing doesn't solve every API problem

Suppose the user searches for laptop, and the API request starts.

Before it finishes, the user changes the search term to laptop stand, triggering another request.

If the first request takes longer than the second, its response could arrive later and overwrite the newer results.

This is a race condition.

You can reduce that risk by cancelling outdated requests.

Here's a more complete version of the component:

import { useEffect, useState } from "react";

function SearchProducts() {
  const [query, setQuery] = useState("");
  const [debouncedQuery, setDebouncedQuery] = useState("");
  const [products, setProducts] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(query.trim());
    }, 500);

    return () => {
      clearTimeout(timer);
    };
  }, [query]);

  useEffect(() => {
    if (!debouncedQuery) {
      setProducts([]);
      setError("");
      return;
    }

    const controller = new AbortController();

    async function fetchProducts() {
      try {
        setError("");

        const response = await fetch(
          `/api/products?search=${encodeURIComponent(debouncedQuery)}`,
          {
            signal: controller.signal,
          }
        );

        if (!response.ok) {
          throw new Error("Unable to fetch products");
        }

        const data = await response.json();

        setProducts(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message || "Something went wrong");
        }
      }
    }

    fetchProducts();

    return () => {
      controller.abort();
    };
  }, [debouncedQuery]);

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        placeholder="Search products..."
      />

      {error && <p>{error}</p>}

      <ul>
        {products.map((product) => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default SearchProducts;

This version adds a few practical improvements:

  • It waits until the user pauses typing.

  • It cancels the previous timer when the input changes.

  • It cancels an outdated fetch when the effect is cleaned up.

  • It handles errors without displaying an error for an intentionally aborted request.

  • It avoids making a request for an empty search term.

The API response format in this example assumes that each product has an id and a name. Adjust the fields to match your backend.

In a larger React application, you might also use a custom useDebounce hook or a data-fetching library that supports cancellation and caching.

7. Implementing Throttling in React

Throttling can be useful in React when an event occurs repeatedly and you need to limit how often a handler executes.

For example, consider a component that tracks scroll position.

A straightforward throttle function can be defined outside the component:

function throttle(callback, delay) {
  let lastExecution = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastExecution >= delay) {
      lastExecution = now;
      callback.apply(this, args);
    }
  };
}

However, React introduces an additional consideration: component rendering and function identity.

If you create a new throttled function on every render, each instance can have its own timer state. That can undermine the intended throttling behavior.

For a simple scroll-position component, you can instead keep the timestamp in a ref:

import { useEffect, useRef, useState } from "react";

function ScrollTracker() {
  const [scrollY, setScrollY] = useState(0);
  const lastExecution = useRef(0);

  useEffect(() => {
    function handleScroll() {
      const now = Date.now();

      if (now - lastExecution.current >= 200) {
        lastExecution.current = now;
        setScrollY(window.scrollY);
      }
    }

    window.addEventListener("scroll", handleScroll, {
      passive: true,
    });

    handleScroll();

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return <p>Scroll position: {scrollY}px</p>;
}

export default ScrollTracker;

Here, useRef() stores the last execution timestamp without triggering a React render whenever the timestamp changes.

The component updates its state only when the configured interval has elapsed.

The event listener is also removed when the component unmounts.

This is a basic example, not a universal solution for every scroll-related task. For animations and frequent visual updates, requestAnimationFrame() may provide better coordination with the browser's rendering cycle.

8. Debouncing and Throttling with requestAnimationFrame()

Sometimes, the goal isn't to limit API requests or delay work until an event stops. Instead, you want visual updates to stay aligned with browser rendering.

For example, you might be updating an element's position while the user scrolls.

Calling expensive layout calculations for every scroll event can create unnecessary work.

requestAnimationFrame() allows the browser to schedule a callback before the next repaint.

A simple example:

let frameRequested = false;

function handleScroll() {
  if (frameRequested) {
    return;
  }

  frameRequested = true;

  requestAnimationFrame(() => {
    frameRequested = false;

    updateScrollIndicator(window.scrollY);
  });
}

window.addEventListener("scroll", handleScroll, {
  passive: true,
});

This implementation avoids scheduling multiple pending animation-frame callbacks at once.

If several scroll events arrive before the next scheduled callback runs, they can be handled by a single update using the latest scroll position.

Unlike a fixed 200-millisecond throttle, this approach coordinates the work with the browser's rendering cycle.

It doesn't guarantee that an expensive function will be cheap, and it doesn't provide a fixed time-based execution interval. The callback may run at a frequency tied to the display's refresh rate.

Use it when the goal is to coordinate visual updates with rendering rather than to enforce a specific time interval.

9. Common Mistakes When Using Debouncing and Throttling

Understanding the concepts is important, but implementation details can cause problems if you're not careful.

Mistake 1: Choosing the wrong delay

A 100-millisecond debounce may still trigger multiple searches while someone types slowly.

A 1,500-millisecond debounce may make a search interface feel unresponsive.

The right delay depends on the use case.

For autocomplete search, developers often start around 300–500 milliseconds and adjust based on user experience, API latency, and the expected typing pattern.

For throttled event handlers, choose an interval based on how frequently the work needs to happen.

Treat these values as starting points, not universal rules.

Mistake 2: Assuming debouncing cancels network requests

Debouncing prevents a scheduled callback from executing if the timer is reset first.

It doesn't automatically cancel a request that has already started.

Use AbortController where supported or another cancellation mechanism provided by your networking library.

Mistake 3: Forgetting cleanup in React

Timers and event listeners should be cleaned up when they are no longer needed.

Otherwise, callbacks may run after a component has unmounted, and listeners can remain attached longer than intended.

Use effect cleanup functions to clear timers, cancel requests, and remove event listeners.

Mistake 4: Creating new throttled functions on every render

If every render creates a new throttle instance, its internal state may reset.

This can cause the callback to execute more frequently than intended.

Keep the function's identity stable where necessary, and make sure it accesses the latest state and props safely.

For complex handlers, a custom hook or a well-maintained utility library can reduce the chance of subtle bugs.

Mistake 5: Using debouncing when continuous updates are required

Imagine a drag-and-drop interface that needs to update an element's position as the pointer moves.

If you debounce the update, the element might not move until the pointer stops.

That creates a poor user experience.

Throttling or requestAnimationFrame() is generally more appropriate when intermediate updates matter.

Mistake 6: Thinking these techniques replace backend protection

Debouncing can reduce unnecessary requests from a well-behaved frontend, but it isn't a security mechanism.

A user or automated client can call your API directly without using your interface.

If an endpoint needs protection from excessive traffic, implement appropriate server-side rate limiting, validation, and monitoring.

Frontend optimization and backend protection solve different problems.

10. Should You Use a Library or Implement These Functions Yourself?

For learning purposes, implementing debounce and throttle from scratch is useful because it teaches you about closures, timers, callback execution, and event handling.

In production applications, a well-maintained utility library can save time and provide more complete behavior.

For example, Lodash provides debounce and throttle utilities with additional options.

A debounced function may support:

  • Leading-edge execution.

  • Trailing-edge execution.

  • A maximum wait time.

  • Cancellation of pending execution.

  • Immediate flushing of a pending callback.

A throttled function may also support leading and trailing execution options.

These options matter in real applications. A simple implementation may be enough for a search field, but it might not satisfy more complex interaction requirements.

Before adding a library, consider whether the project already includes a utility package and whether its behavior matches your requirements.

Also, remember that the examples in this article intentionally demonstrate the core concepts. They aren't drop-in replacements for every feature offered by a mature utility library.

Conclusion

Debouncing and throttling are small techniques that can make a noticeable difference in JavaScript applications.

Debouncing is useful when you want to wait for activity to pause before executing a function. Search suggestions, form validation, and recalculating a layout after resizing are common examples.

Throttling is useful when you want to limit how frequently a function executes while activity continues. Scroll tracking, periodic event processing, and certain resize handlers are good examples.

The most important thing is to understand the behavior you need before choosing an approach.

If you need the final input value after the user stops typing, debounce is usually the right choice. If you need controlled updates while an event continues, throttling may be more suitable. And if you're coordinating visual updates with browser rendering, requestAnimationFrame() deserves consideration.

Once you understand these differences, you'll find plenty of opportunities to apply them in React applications, dashboards, search interfaces, and other interactive web applications.

They're simple concepts, but knowing when and how to use them is an important part of writing efficient frontend code.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘
What Are Promises in JavaScript?
•17m

What Are Promises in JavaScript?

In JavaScript, a Promise is an object that represents the eventual success or failure of an asynchronous operation. Promises help you manage operations such as…

30