JavaScript: Debouncing vs. Throttling

Shameel Uddin - Oct 11 '23 - - Dev Community

Introduction

When working with JavaScript, you often encounter scenarios where you need to handle events such as scrolling, resizing, or typing. Two common techniques for managing these events are debouncing and throttling. In this blog, we'll explore the differences between debouncing and throttling, along with practical examples in JavaScript.

Debouncing vs. Throttling

We will first try to understand the use-case of both and then understand a real-world example.

Use Case:

  • Use debouncing when you want to delay the execution of a function until a user stops interacting with an element. This is suitable for scenarios like autocomplete suggestions or real-time search.

  • Use throttling when you want to limit the rate at which a function can be called. It's ideal for handling events like scrolling, resizing, or mouse movement.

Example

For a real world example when user is typing in an input and the delay is 1 second, then:

  • In debouncing, the function will be executed after 1 second when the user stops typing. This means that if the user continues to type within the 1-second delay, the function execution will be postponed until there is a 1-second pause in typing.

    • It's executed once.
  • In throttling, the function will be executed after every 1 second at regular intervals if the user keeps triggering the event. Throttling allows the function to be executed at regular intervals (e.g., every 1 second), as long as the user keeps triggering the event.

    • It limits the frequency of function calls, ensuring it doesn't execute too often, even if the event is fired frequently.

Debouncing And Throttling Example App:

Demo

https://typescript-4bmhoq.stackblitz.io/

Open the console, keep firing the buttons and try to observe the behavior.

  • If you keep clicking on Debounce without delay, you will see that the event does not get fired until you stop.
  • If you keep clicking on Throttle without delay, you will see that the event keeps getting fired at regular interval of 1 second.

app-example

If this app does not work in future then go to stackblitz, paste the code provided below and observe it.

Code

HTML:

<div id="app">
  <h1>Example for Debouncing and Throttling.</h1>
<li>
  If you keep clicking on Debounce without stopping, you will see that the event does not get fired until you stop clicking.</li>
  <li>
    If you keep clicking on Throttle without delay, you will see that the event keeps getting fired at regular interval of 1 second.
</li></br>
<p>Click button and observe the behavior in console.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

TypeScript:

// Import stylesheets
import './style.css';

// Write Javascript code!
const appDiv = document.getElementById('app');

function handleClick(type) {
  return function () {
    console.log(type, 'clicked!!!');
  }
}
function debounce(func, delay) {
  let debounceTimer;
  return (...args) => {
    clearTimeout(debounceTimer);
    const that = this;
    debounceTimer = setTimeout(() => func.apply(that, args), delay);
  };
}

function throttle(func, delay) {
  let debounceTimer;
  return (...args) => {
    const that = this;
    if (!debounceTimer) {
      debounceTimer = setTimeout(() => {
        func.apply(that, args);
        debounceTimer = null;
      }, delay);
    }
  };
}

const DebouncedHandleClick = debounce(handleClick('Debounced'), 500);
const ThrottledHandleClick = throttle(handleClick('Throttled'), 500);

const button1 = document.createElement('button');
const button2 = document.createElement('button');
button1.innerHTML = 'Debounce action dispatcher';
button1.addEventListener('click', DebouncedHandleClick);
button2.innerHTML = 'Throttle action dispatcher';
button2.addEventListener('click', ThrottledHandleClick);
appDiv.append(button1);
appDiv.append(button2);

Enter fullscreen mode Exit fullscreen mode

Conclusion

Debouncing and throttling are essential techniques when working with JavaScript events. They help optimize performance and provide a better user experience by controlling the frequency of function execution. Understanding the differences between these two methods and choosing the right one for your specific use case is crucial for building efficient and responsive web applications.

Happy coding! 🎉💻✨

Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player