DEV Community

Cover image for Javascript Throttling & Debouncing πŸš€
Shivam Singh
Shivam Singh

Posted on β€’ Edited on

3 1 1 1 1

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.


SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs