DEV Community

Cover image for Debouncing vs. Throttling: Don't Let Your Code Misbehave! ๐Ÿ•๐Ÿš€
Priya Pandey
Priya Pandey

Posted on

Debouncing vs. Throttling: Don't Let Your Code Misbehave! ๐Ÿ•๐Ÿš€

Have you ever clicked a button multiple times and suddenly realized your app glitched or made too many API calls? Maybe you've typed in a search bar, and it kept sending requests after every letter?

Thatโ€™s when debouncing and throttling come to the rescue! ๐Ÿš€

These two JavaScript techniques control how frequently your function executes, making your app faster, smoother, and bug-free. Today, weโ€™ll break them down in a fun, pizza-themed wayโ€”because who doesnโ€™t love pizza? ๐Ÿ•๐Ÿ”ฅ

๐Ÿ• Debouncing: "Ek Baar Bolna, Baar Baar Nahi!" (Say it once, not again and again!)

Imagine you're at a pizza restaurant, and you have a habit of changing your order every second:

  • "Ek Margherita dedo!"(Give me one Margherita!)
  • "Nahi nahi, ek Pepperoni dedo!" (No no, give me one Pepperoni!)
  • "Wait, ek Farmhouse dedo!"(Wait, give me one Farmhouse!)
  • "Arey, nahi! Cheesy Burst chahiye!"(Oh no! I want Cheesy Burst!)

What happens? ๐Ÿคฆโ€โ™‚๏ธ
The waiter gets confused and doesn't place the order until you're finally done deciding. He waits for you to stop changing your mind before sending the order to the kitchen.

This is Debouncing. ๐Ÿ’ก

function debounce(orderFunction, delay) {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(orderFunction, delay); // Execute after delay
  };
}
function acceptOrder() {
  console.log("Pizza order accepted! ๐Ÿ•");
}

const orderButton = document.getElementById("orderButton");
orderButton.addEventListener("click", debounce(acceptOrder, 3000));
Enter fullscreen mode Exit fullscreen mode

Don't ask how timer is still available for our order. Please have a proper closure with THE CLOSURE from the one and only Akshay Saini

๐Ÿ“ What Happens?

If you click multiple times within 3 seconds, the function wonโ€™t execute.
It only executes after you stop clicking for 3 seconds.
โœ… Perfect for search bars, form submissions, or anything that shouldnโ€™t trigger too frequently!


โณ Throttling: "Limit Cross Mat Karo Bhai!"(Don't Cross the Limit, Bro!)

Now imagine another scenario:

Youโ€™re super hungry and start shouting at the waiter every second:

  • "Bhai, pizza lao!"(Bro, bring the pizza!)
  • "Bhai, pizza lao!"(Bro, bring the pizza!)
  • "Bhai, pizza lao!"(Bro, bring the pizza!)

The waiter finally loses patience and tells you:
๐Ÿ‘‰ "Aap jitni baar bhi bolo, main sirf har 5 second me ek baar order loonga!"(No matter how many times you ask, I'll only take one order every 5 seconds!)

This is Throttlingโ€”even if you keep spamming the button, the function will only execute once in a fixed time interval.

function throttle(orderFunction, duration) {
  let lastExecutionTime = 0;
  return function () {
    const currentTime = Date.now();
    if (currentTime - lastExecutionTime >= duration) {
      orderFunction();
      lastExecutionTime = currentTime;
    }
  };
}
function acceptOrder() {
  console.log("Pizza order placed! ๐Ÿ•");
}

const orderButton = document.getElementById("orderButton");
orderButton.addEventListener("click", throttle(acceptOrder, 5000));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ What Happens?

If you click 10 times within 5 seconds, the function runs only ONCE.
After 5 seconds, the function runs again if clicked.
โœ… Perfect for API rate limiting, scrolling, or any function that should execute at fixed intervals!


For our readers who want more like our pizza customers.

๐Ÿ‘‰ Thatโ€™s what our basic debounce function did. But now, introducing Debounce 2.0 โ€“ The Advanced Edition! ๐Ÿš€

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

๐Ÿ˜’Don't fuss I have Throttle SUPERCHARGED Version as well.

function throttle(func, limit) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= limit) {
      func.apply(this, args);
      lastCall = now;
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

Try it out and save your CPU from unnecessary drama.๐Ÿ˜ฎโ€๐Ÿ’จ

Top comments (2)

Collapse
 
bharanidharan_natarajan_1 profile image
Bharanidharan Natarajan

Nice article

Collapse
 
priya2422 profile image
Priya Pandey

Glad you read and liked it.