DEV Community

Jakaria Masum
Jakaria Masum

Posted on

Understanding Throttle in JavaScript

If you’ve ever worked with JavaScript and added event listeners (like scroll or resize), you might have noticed that your code runs too often, which can slow things down. This is where throttle comes to the rescue!

In this post, we’ll break down what throttling is, why it’s useful, and how to implement it — with a fun real-life example to help you visualize it.


What is Throttling?

Throttling means limiting how often a function can run.

Imagine you’re at a concert, and the security guard checks tickets at the entrance. Even if 100 people rush in at once, the guard can only check one ticket every 2 seconds. That’s throttling — it controls the rate of a repetitive action.

In JavaScript, throttling ensures that a function can only run once in a specified time period, no matter how many times it’s triggered.


Why Do We Need Throttling?

Some events in the browser can fire many times per second, such as:

  • scroll
  • resize
  • mousemove
  • keydown

If you attach a function to these events without throttling, the function might run hundreds or thousands of times in a short period! This can cause:

  • Slow performance
  • Laggy interfaces
  • High CPU usage

Throttling helps keep your app fast and smooth by controlling how often the event handler runs.


How Throttling Works (With Code)

Here’s a simple throttle function:

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

How to use it:

function onScroll() {
  console.log("Scroll event handler called at", new Date().toISOString());
}

window.addEventListener("scroll", throttle(onScroll, 1000)); 
// This will log at most once every 1000ms, no matter how fast you scroll
Enter fullscreen mode Exit fullscreen mode

Real-Life Example: Throttling Window Resize

Let’s say you have a dashboard, and you want to recalculate layout sizes whenever the window is resized. Without throttling, the handler might run dozens of times as you drag the window. Let’s throttle it!

function updateLayout() {
  console.log("Updating layout at", new Date().toISOString());
  // Imagine some expensive calculations here
}

window.addEventListener("resize", throttle(updateLayout, 500));
// Layout updates no more than once every 500ms
Enter fullscreen mode Exit fullscreen mode

Real-life analogy:
Think of this like adjusting your seat while driving. You don’t adjust your seat position every microsecond as you move — you pause, assess, and adjust every few moments. Throttling does the same for your code!


When to Use Throttle?

Scroll events — e.g., loading more content as you scroll down.
Resize events — e.g., adjusting layout or graphics size.
Mouse move or drag — e.g., drawing tools, sliders.


Final Thoughts

Throttle helps you control how often a function runs, making your app more efficient and smooth.

Whenever you’re working with high-frequency events, consider using throttle to keep performance in check!


Bonus Tip

There are libraries like Lodash that give you a ready-made _.throttle function — super handy!

import throttle from 'lodash/throttle';

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

Summary

  • Throttling limits how often a function can run in a given time frame.
  • It’s great for scroll, resize, mousemove, and similar events.
  • It keeps your app smooth and prevents unnecessary work.

Top comments (0)