DEV Community

Cover image for Javascript Throttling & Debouncing 🚀
Shivam Singh
Shivam Singh

Posted on • Edited on

Javascript Throttling & Debouncing 🚀

Why Throttle or Debounce? ðŸĪ”
Welcome back, code ninjas! ðŸĨ· Ever faced a situation where your application starts acting like a toddler on a sugar rush? Yep, over-excited and out of control! Well, that's probably because it's choking on too many events. Enter throttling and debouncing, your new BFFs! 😎


1ïļâƒĢ What Even is Throttling? ðŸĒ

Throttling is like that friend who tells you to chill when you're hyperventilating. It limits how many times a function can be executed over a given period.

function throttle(func, delay) {
  let lastCall = 0;
  return function() {
    const now = new Date().getTime();
    if (now - lastCall < delay) return;
    lastCall = now;
    return func.apply(this, arguments);
  };
}
Enter fullscreen mode Exit fullscreen mode

Try this with a scrolling event and see your console relaxing instead of flooding!

2ïļâƒĢ Debouncing: The Thoughtful One ðŸĪŦ

Debouncing is the thinker in your group. It doesn't jump into action; it waits for the right moment. This is great for search box suggestions, for instance.

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

Try this out when you want to wait for the user to stop typing before making an API call.


3ïļâƒĢ Throttling vs Debouncing: The Eternal Debate ðŸĨŠ

Here's where we throw them in the ring together. Throttling is like a metronome; it's rhythmic. Debouncing is the "freeze, let me think" kind. Use throttling for real-time stuff and debouncing for when waiting is okay.
Example: Imagine a real-time search feature on a website. With throttling, you get updates as you type, but not every keystroke triggers an API call. With debouncing, the search won't start until you've stopped typing for a moment.

// Throttling for real-time feel
document.querySelector("#realTimeSearch").addEventListener("input", throttle(function() {
  console.log("Throttled real-time search!");
}, 500));

// Debouncing for thoughtful responses
document.querySelector("#thoughtfulSearch").addEventListener("input", debounce(function() {
  console.log("Debounced search!");
}, 500));
choices.
Enter fullscreen mode Exit fullscreen mode

4ïļâƒĢ Use Cases: Throttling in the Wild ðŸŒē

Scroll events, mouse move events, or any continuous event can benefit from throttling. Your CPU will thank you!

window.addEventListener("scroll", throttle(function() {
  console.log("Throttled scroll!");
}, 200));
Enter fullscreen mode Exit fullscreen mode

5ïļâƒĢ Use Cases: Debouncing For The Win 🏆

Great for text input or combo boxes where you don't want to start searching or filtering until the user has finished typing.

const searchBox = document.querySelector("#search");
searchBox.addEventListener("keyup", debounce(function() {
  console.log("Debounced search!");
}, 300));
Enter fullscreen mode Exit fullscreen mode

6ïļâƒĢ How to Implement Using Lodash 📚

Oh, you're lazy, huh? Well, good news! Libraries like Lodash have these features built in. Just import and go!

import { throttle, debounce } from 'lodash';

// Throttle button click
document.querySelector("#myButton").addEventListener("click", throttle(function() {
  console.log("Button clicked, but throttled!");
}, 1000));

// Debounce autocomplete
const autoCompleteBox = document.querySelector("#autoComplete");
autoCompleteBox.addEventListener("keyup", debounce(function() {
  console.log("Debounced autocomplete search!");
}, 300));

// Use like a pro
Enter fullscreen mode Exit fullscreen mode

7ïļâƒĢ Gotchas and Mistakes to Avoid ðŸšŦ

Be careful when applying these techniques. Overdoing it may lead to sluggish behavior, and nobody likes a slowpoke! 🐌

// Don't throttle or debounce EVERYTHING!
Enter fullscreen mode Exit fullscreen mode

8ïļâƒĢ The Future: RequestAnimationFrame ðŸŽĨ

The requestAnimationFrame method gives you more control and can be more efficient than both throttling and debouncing for certain tasks like animations.

function animate() {
  console.log("Animating!");
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Enter fullscreen mode Exit fullscreen mode

Conclusion: Are You a Throttling and Debouncing Ninja Yet? ðŸĪš

You've just had a crash course in throttling and debouncing, tools that can significantly optimize your JS performance. Don't forget to leave a comment with your own tips or questions.


Top comments (0)