Debouncing in JavaScript

Ever noticed how a search box or resize event can trigger a function dozens of times per second (𝐞.𝐠 𝐟𝐥𝐢𝐩𝐤𝐚𝐫𝐭 𝐬𝐞𝐚𝐫𝐜𝐡𝐛𝐨𝐱)?

Calling APIs or heavy logic on every keystroke is inefficient and costly.

That’s where Debouncing comes in 👇

Debouncing is a common JavaScript technique used to control how often a function executes. Instead of running a function every time an event fires, debouncing ensures it runs only after the event stops firing for a certain period.

This article focuses on how debouncing is implemented, step by step.

𝐃𝐞𝐛𝐨𝐮𝐧𝐜𝐢𝐧𝐠 𝐞𝐧𝐬𝐮𝐫𝐞𝐬 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐬 𝐨𝐧𝐥𝐲 𝐚𝐟𝐭𝐞𝐫 𝐚 𝐜𝐞𝐫𝐭𝐚𝐢𝐧 𝐝𝐞𝐥𝐚𝐲 𝐡𝐚𝐬 𝐩𝐚𝐬𝐬𝐞𝐝 𝐬𝐢𝐧𝐜𝐞 𝐭𝐡𝐞 𝐥𝐚𝐬𝐭 𝐞𝐯𝐞𝐧𝐭.

The Core Idea Behind Debouncing-

At its core, debouncing relies on three concepts:

  1. Closures to remember the state between calls.
  2. Timers (setTimeout) to delay execution.
  3. Timer cancellation (clearTimeout) to prevent previous executions.

Each new call cancels the previous scheduled execution and schedules a new one.

If the event keeps firing, the previous execution is cancelled - only the final one runs.

Debounce Implementation-

function debounce(fn, delay) {
  let timerId;

  return function (...args) {
    const context = this;
    // capture the current calling context to preserve `this` inside fn
    clearTimeout(timerId);

    timerId = setTimeout(() => {
      fn.apply(context, args); // apply invokes the original function with the same `this` context and forwards all arguments correctly
    }, delay);
  };
}

function fetchData(query, method) {
  console.log("Fetching Data for", query, "method=", method, "...");
}

const debouncedFetch = debounce(fetchData, 300);

const inputField = document.getElementById("search-input");

inputField.addEventListener("input", function (e) {
  debouncedFetch(e.target.value, Date.now());
});
        

𝐖𝐡𝐲 𝐢𝐭 𝐦𝐚𝐭𝐭𝐞𝐫𝐬:

  1. 𝐑𝐞𝐝𝐮𝐜𝐞𝐬 𝐮𝐧𝐧𝐞𝐜𝐞𝐬𝐬𝐚𝐫𝐲 𝐀𝐏𝐈 𝐜𝐚𝐥𝐥𝐬
  2. 𝐈𝐦𝐩𝐫𝐨𝐯𝐞𝐬 𝐔𝐈 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞
  3. 𝐏𝐫𝐞𝐯𝐞𝐧𝐭𝐬 𝐞𝐯𝐞𝐧𝐭 𝐟𝐥𝐨𝐨𝐝𝐢𝐧𝐠
  4. 𝐂𝐫𝐞𝐚𝐭𝐞𝐬 𝐬𝐦𝐨𝐨𝐭𝐡𝐞𝐫 𝐮𝐬𝐞𝐫 𝐞𝐱𝐩𝐞𝐫𝐢𝐞𝐧𝐜𝐞

💡 𝐂𝐨𝐦𝐦𝐨𝐧 𝐮𝐬𝐞 𝐜𝐚𝐬𝐞𝐬:

  • Search suggestions
  • Input validation
  • Window resize / scroll handlers
  • Button click protection

𝑰𝒏 𝒔𝒉𝒐𝒓𝒕: 𝑫𝒆𝒃𝒐𝒖𝒏𝒄𝒊𝒏𝒈 𝒅𝒐𝒆𝒔𝒏’𝒕 𝒄𝒉𝒂𝒏𝒈𝒆 𝒘𝒉𝒂𝒕 𝒂 𝒇𝒖𝒏𝒄𝒕𝒊𝒐𝒏 𝒅𝒐𝒆𝒔 - 𝒊𝒕 𝒄𝒉𝒂𝒏𝒈𝒆𝒔 𝒘𝒉𝒆𝒏 𝒊𝒕 𝒓𝒖𝒏𝒔.

To view or add a comment, sign in

Explore content categories