Skip to main content

Command Palette

Search for a command to run...

How to Use Debouncing and Throttling in JavaScript: Step-by-Step Guide

A Clear Comparison of Debouncing and Throttling with Practical Code Examples

Updated
3 min read
How to Use Debouncing and Throttling in JavaScript: Step-by-Step Guide

When building modern web applications, one common challenge is performance optimization. Think about actions like scrolling, resizing the window, or typing rapidly in an input field—these events can fire dozens of times per second. If every event triggers heavy computations or API calls, your app will lag and your users will run away faster than you can say “JavaScript”!

That’s where debouncing and throttling come to the rescue. Let’s break them down with simple explanations and real-world examples you can relate to.

» What is Debouncing?

» Debouncing ensures that a function executes only after a certain period of inactivity.
It’s like saying: “Don’t bother me until you’ve stopped doing that action for a moment.”


Real-Life Example: Elevator Button

Ever noticed how people keep pressing the elevator button multiple times? But the elevator only responds once after the presses stop. That’s debouncing!

» Code Example: Debounced Notification Sender

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

// Example: Sending notification only when user stops typing
const notifyUser = debounce((msg) => {
  console.log(`📩 Notification Sent: ${msg}`);
}, 1500);

// Simulating typing activity
const messages = ["Hel", "Hello", "Hello W", "Hello Wo", "Hello World!"];

let i = 0;
const interval = setInterval(() => {
  notifyUser(messages[i]);
  i++;
  if (i === messages.length) clearInterval(interval);
}, 400);

📝 How this works:

  • User types continuously.

  • Instead of sending a notification for every keystroke, it waits until the user pauses for 1.5 seconds before sending the final message.


What is Throttling?

👉 Throttling ensures that a function executes at most once within a specified time interval.
It’s like saying: “I’ll handle your request, but only once every X milliseconds, no matter how many times you ask.”

» Real-Life Example: Traffic Police at a Busy Junction

Imagine a traffic cop who only lets cars move forward every 10 seconds. Even if 100 cars honk in between, only the next batch moves after the fixed interval.

» Code Example: Throttled GPS Tracker


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

// Example: GPS location tracking (updates at most once per 2s)
const updateLocation = throttle((coords) => {
  console.log(`📍 User Location Updated: ${coords}`);
}, 2000);

// Simulating rapid GPS updates
let step = 1;
const gpsInterval = setInterval(() => {
  updateLocation(`Lat: 40.${step}, Lng: -74.${step}`);
  step++;
  if (step === 8) clearInterval(gpsInterval);
}, 500);

📝 How this works:

  • Even though location updates come in every 0.5 seconds,

  • The app only updates once every 2 seconds, saving battery and bandwidth.


When to Use What?

  • Debounce → When you want the action to happen only after the user stops.

    » Example: Search box, form validation, saving drafts.

  • Throttle → When you want the action to happen at regular intervals while the event is continuously firing.

    » Example: Scroll events, GPS tracking, window resizing.

🎯 Final Thoughts

Debouncing and throttling may sound like technical jargon, but in reality, they’re just smart time managers for your JavaScript functions. Use them wisely, and your apps will feel smoother, faster, and more professional.

Next time you’re coding, remember:

  • Debounce = “Wait until I stop.”

  • Throttle = “Do it, but not too often.”


If you found this helpful, don’t just keep it to yourself—share it with your developer friends or try implementing it in your next project. Your users (and your browser’s CPU) will thank you!

📝 Now it’s your turn!
Did you enjoy this article? Then go ahead and share it, drop a comment, and give it a like 💡
Got questions or want me to cover a related topic? 🚀 Leave your thoughts below—I’ll do my best to get back to you!