debounce-vs-throttle-javascript

Debounce vs Throttle in JavaScript: A Beginner’s Guide with examples

Understand what debounce or throttle a JavaScript function means and the differences with code examples.

Reading time: 4'

0 likes
Published on October 07, 2024

JavaScript provides powerful tools to manage how frequently a function gets executed in response to user interactions, such as scrolling, typing, or resizing a window. Two such tools are debounce and throttle. These concepts help improve performance by controlling the frequency of function execution, especially when dealing with events that trigger frequently.

In this guide, we’ll break down what debounce and throttle are, how to implement them, and when to use one over the other.


What is Debouncing in JavaScript?

Debounce is a technique used in JavaScript to limit how often a function can execute after a sequence of rapid, continuous events. It ensures that a function is called only after a certain amount of time has passed without the event being triggered again.

Debouncing is especially useful when the event handler is invoked multiple times in quick succession (such as keystrokes in a search box) and you only want to take action when the user stops interacting.

Use case for Debounce

Imagine a user typing into a search bar that triggers an API call to fetch search results. Without debounce, every single keystroke would send a request, which would be inefficient. With debounce, the request will only be made after the user stops typing for a certain duration, avoiding unnecessary API calls.


How to delay a function with Debounce in JavaScript

Custom Debounce implementation

Here's a simple example of how to implement debounce manually in JavaScript.

function debounce(func, delay) { let timeout; return function (...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), delay); }; } // Example usage: const handleInput = () => { console.log('Fetching search results...'); }; const debouncedInput = debounce(handleInput, 300); document.querySelector('input').addEventListener('input', debouncedInput);

In this example:

  • The debounce function takes two arguments: the function to be debounced and the delay in milliseconds.
  • setTimeout ensures that the function will only execute after the user has stopped typing for the specified delay (300ms).

Using libraries for Debounce

JavaScript libraries like Lodash and Underscore.js provide built-in debounce functions that simplify the process.

Lodash Example:

const _ = require('lodash'); const handleInput = () => { console.log('Fetching search results...'); }; const debouncedInput = _.debounce(handleInput, 300); document.querySelector('input').addEventListener('input', debouncedInput);

With Lodash, the same functionality is achieved with far fewer lines of code, and it provides cross-browser compatibility.


What is Throttling in JavaScript?

Throttling ensures that a function is called at most once in a specified time period, no matter how many times an event is triggered. It guarantees a consistent flow of function executions at regular intervals, which is particularly useful for events that can fire continuously, like scrolling or resizing.

Use case for Throttle

Imagine you want to track how far down the page a user scrolls. If you update the scroll position every time the event fires, you might overload the browser with updates. Throttling allows you to measure the scroll position at set intervals (for example, every 200ms) to avoid unnecessary computations.


How to throttle function execution in JavaScript

Custom Throttle implementation

Here’s how you can create a custom throttle function in JavaScript:

function throttle(func, limit) { let inThrottle; return function (...args) { if (!inThrottle) { func.apply(this, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } // Example usage: const trackScroll = () => { console.log('Tracking scroll position...'); }; const throttledScroll = throttle(trackScroll, 200); window.addEventListener('scroll', throttledScroll);

In this implementation:

  • throttle takes the function and the time limit (in milliseconds) as arguments.
  • The function will only be executed once within the defined limit (200ms), even if the scroll event fires multiple times.

Using libraries for Throttle

Similar to debounce, you can use Lodash or Underscore.js to easily implement throttle.

Lodash Example:

const throttledScroll = _.throttle(() => { console.log('Tracking scroll position...'); }, 200); window.addEventListener('scroll', throttledScroll);

This version ensures that the function is executed no more than once every 200ms, even if the user scrolls continuously.


What is the difference between Debounce and Throttle in JavaScript?

Debounce and throttle are both techniques used to control the frequency of function execution in response to rapid event triggers, but they have distinct purposes and behaviors.

AspectDebounceThrottle
PurposeDelays function execution until a certain time has passed without further events.Ensures function execution at regular intervals, regardless of how many events occur.
Best Use CasesInput validation, search autocomplete, window resizing.Scroll tracking, infinite scrolling, monitoring mouse movements.
How it WorksExecutes the function only once after a period of inactivity.Ensures a consistent execution rate by limiting the function calls.
FrequencyFunction is called after the event stream ends.Function is called at regular intervals while events are still occurring.
ExampleTyping in a search box (API call triggered after typing stops).Handling scroll events (tracking position every 200ms).

When to Use Debounce

  • Debouncing is ideal when you want to delay the execution of a function until a user stops performing an action. Use it when you expect bursts of events and only need the final action to trigger your function, such as in search input fields or resizing windows.

When to Use Throttle

  • Throttling is more appropriate when you need to control how often a function is called in response to continuous events, like scrolling or mouse movement. Use it to maintain a smooth and consistent user experience by limiting how often an expensive function executes.

Recap the differences between Debounce and Throttle in JavaScript

Understanding the difference between debounce and throttle can significantly improve the performance and responsiveness of your JavaScript applications. Use debounce when you want to wait for a user to stop triggering an event, and opt for throttle when you need to enforce a regular execution interval regardless of how often the event occurs.

Mastering these techniques will make your web applications more efficient and responsive to user interactions.

In case you think this content deserves to be shared, it would be great if you could support me just doing at least one of the following actions:

  • Leave a like
  • Leave a comment
  • Share the article
  • Spread the voice with your friends

Articles related to JavaScript

Courses of JavaScript

  • Masterclass19% off
    Max 6 students
    Masterclass JavaScript

    Building a scalable app with NextJS and GraphQL

    NextJS, Graphql, Tailwind and Strapi. The most important technologies in a single masterclass.

    • JavaScript
    • NextJS
    More info
  • Masterclass
    Max 10 students
    React masterclass

    Build your portfolio with ReactJS and Typescript

    Master ReactJS and Typescript by building your own portfolio with NextJS in only 12.5 hours.

    • JavaScript
    • NextJS
    More info

Newsletter

Subscribe to the newsletter to receive updates about programming news, course discounts, and other content published on the platform.
You will get instantly a 10% discount.