DEV Community

Rova Ranaivo
Rova Ranaivo

Posted on

Understanding JavaScript Debounce and Throttling

Javascript, a dynamic and versatile language, provides several powerful features. Two such features, debounce and throttling, help enhance the performance of your web applications, particularly when dealing with events like scrolling, resizing, or key presses. However, many developers find these concepts somewhat tricky to grasp. Let's simplify them.

What is Debouncing?

Imagine you're in an elevator. You keep pressing the button, but the elevator won't close any faster. It waits until there's a noticeable pause between button presses. This is debouncing. In JavaScript, debouncing is a technique where we group multiple sequential calls in one single call.

For example, if you're listening to the scroll event, which fires hundreds of times per minute, using a debounce function will ensure that your actual event handling function only runs once after the user has stopped scrolling.

Here's an example of a debounce function in JavaScript:

function debounce(func, delay) {
  let debounceTimer;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => func.apply(context, args), delay);
  }
}

window.addEventListener('scroll', debounce(function() {
  console.log('Scrolling');
}, 300));
Enter fullscreen mode Exit fullscreen mode

In this example, our debounce function will execute the console log only once every 300ms during a scroll, rather than for every pixel scrolled.

What is Throttling?

Throttling, on the other hand, ensures that a function doesn't run more often than the delay time. It's like a pipe, limiting the amount of water flowing through it. This is useful for situations where you don't want to wait until the event stops firing, but still want to limit the amount of times your function runs.

Here's a basic throttling function:

function throttle(func, limit) {
  let inThrottle;
  return function() {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  }
}

window.addEventListener('scroll', throttle(function() {
  console.log('Scrolling');
}, 300));
Enter fullscreen mode Exit fullscreen mode

In this case, the console log will only fire every 300ms during a scroll, not waiting for the scroll to end.

Conclusion

Debouncing and throttling are powerful techniques that can optimize the performance of your web applications. By controlling the rate at which events trigger function execution, you can significantly enhance user experience and efficiency. Remember, debouncing is like waiting for the elevator door to close, and throttling is like controlling the flow of water through a pipe.

Next time you're faced with rapidly firing events, consider using debouncing or throttling to optimize your function calls.

Heroku

The AI PaaS for deploying, managing, and scaling apps.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Get Started

Top comments (0)

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Show your support for this compelling post and become part of the vibrant DEV Community. All levels of coders can share insights and build collective wisdom.

Even a brief “thank you” can brighten an author’s day. Drop your kudos below!

At DEV, sharing know-how paves the way and strengthens connections. If this article resonated with you, a quick note of thanks goes a long way.

Count me in!