Throttling Technique in JavaScript with a real example.

Ronak MathurRonak Mathur
3 min read

By using the throttle technique, we can optimize the performance of our website. It could be one of the best practices when building smooth and high-performing frontend applications.

Throttling

Throttling technique used to limit the rate at which a function is called or executed. It ensures that the function is invoked at most once, regardless of how many times users intentionally or unintentionally invoke it, optimizing performance in scenarios where events, like scroll, resize, or mousemove, can trigger functions frequently, potentially causing performance issues or excessive resource consumption.

Popular apps like Facebook, Instagram, and YouTube use infinite scrolling to continuously load more content as you scroll, creating a seamless, endless experience.

Why Use Throttle?

In JavaScript, throttle is used when:

  • You want to limit how often a function runs (like scroll or resize).

  • You want to skip extra calls or run only the latest one to avoid overload.

Before we start, let's build a simple data-fetching app where we fetch data from a fake API.

I have implemented the infinite scroll functionality below using vanilla JS.

  const products = document.querySelector(".products");
  const loadmore = document.querySelector(".load");
  const productUrl = "https://dummyjson.com/products"; // i have used dummy api to fetch data
  let limit = 5;
  let skip = 0;
  let isFetching = false;
  let hasMore = true;

  // function to fetch product from api
  loadProducts(productUrl, limit, skip); // when first time page load to fetch data
  async function loadProducts(url, limit, skip) {
    loadmore.style.display = "block";
    if (isFetching || !hasMore) return;
    try {
        isFetching = true;
        const data = await fetch(`${url}?limit=${limit}&skip=${skip}`, {
          method: "get",
        });
        const response = await data.json();

        if (response.products.length === 0 || !response.products) {
          hasMore = false;
          return;
        }

        response.products.forEach((item) => {
          const content = document.createElement("div");
          const desc = document.createElement("p");
          const title = document.createElement("h2");
          const image = document.createElement("img");
          title.textContent = item.title;
          image.src = item.images[0];
          desc.textContent = item.description;
          content.id = item.id;
          content.className = "product";

          content.appendChild(title);
          content.appendChild(image);
          content.appendChild(desc);
          products.appendChild(content);
        });
        isFetching = false;
    } catch (error) {
        console.error("error while fetching ", error.message);
    } finally {
        loadmore.style.display = "none";
    }
  }

// Note.
// this fake api does not support current page query parameter in api url
// so i used skip and limit params to load the data while scrolling page...

Let’s create a utility function for throttling

function throttleScroll(func, delay) {
  let isWaiting = false; // current throttle check
  return function (...args) {
    if (isWaiting) return;

    func(...args);
    isWaiting = true;
    setTimeout(() => {
      isWaiting = false;
    }, delay);
  };
}

Let’s delve into a real-world example to demonstrate how to effectively apply the throttle technique to optimize our application, specifically focusing on implementing an infinite scrolling feature. This feature allows users to continuously load new content as they scroll down the page, creating a seamless browsing experience. By using throttling, we can ensure that the function responsible for fetching and displaying new content is not called excessively, which could otherwise lead to performance bottlenecks or unnecessary strain on system resources. This approach not only enhances the user experience by providing smooth and efficient content loading but also helps maintain the overall performance and responsiveness of the application.

Let's wrap our loadProducts function with a throttle utility function.

const scrollDelay = throttleScroll(() => {
  loadProducts(productUrl, limit, skip);
}, 1000);

Finally, Call the Throttle Function on Scroll

To finish setting up throttling, just connect your throttle function to the scroll event like this:

const handleDataOnScroll = () => {
  if (
    window.scrollY + window.innerHeight >=
    document.documentElement.scrollHeight
  ) {
    skip += limit;
    scrollDelay();
  }
}

window.addEventListener("scroll", handleDataOnScroll);

We've now combined scroll detection with throttling to build an efficient infinite scroll, limiting unnecessary API calls, improving performance, and delivering a smoother user experience.

In this article, we have covered and understood the real-world example of throttling using the infinite scroll feature.

Hope you liked it.

Keep Shining, Keep Growing 🌟🌟🌟

Wishing you the best career journey ahead…

1
Subscribe to my newsletter

Read articles from Ronak Mathur directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ronak Mathur
Ronak Mathur