How to Debounce JavaScript Functions to Boost Performance

We will see what debouncing is and how we can implement it using a real world example like handling a resize event on the browser window. I have written a sort of example here in which we are having a function named reportNewWidth, and whenever this function gets called it will print a line showing the current width. You can also have any function or a large amount of code inside this function. This is doing what it is actually printing the inner width of the window size, that is your browser. We have also attached a listener so that every time the size of your window changes, the handler runs and calls this function. That means every time you change the size of your browser, this line of code will execute.

JavaScript Function Debouncing

  How to Debounce JavaScript Functions to Boost Performance  7  

JavaScript Function Debouncing with a resize example

  How to Debounce JavaScript Functions to Boost Performance  3   Here is the starting point that calls the function on every resize. It shows how quickly the event can trigger and how many times the function will run.   How to Debounce JavaScript Functions to Boost Performance  5  
function reportNewWidth() {
  console.log("New width is:", window.innerWidth);
}

window.addEventListener("resize", reportNewWidth);
  How to Debounce JavaScript Functions to Boost Performance  2   Imagine if I am having a large amount of code here, or some heavy function, and it gets called every time the window gets resized. It will be bulky to run and it will execute a large number of times. The resize event fires very frequently, and this can flood your function calls.   How to Debounce JavaScript Functions to Boost Performance  4  

Why repeated calls are a problem

  How to Debounce JavaScript Functions to Boost Performance  6   You can see how many times a resize handler can execute just because I am resizing the window. You do not want your code to run like this. _Debouncing_ means waiting until a series of rapid events is stopped before the actual running code executes. For example, the _window.resize_ event fires dozens of times per second. With debouncing we wait until the user stops resizing before doing our work.

Implementing JavaScript Function Debouncing

  How to Debounce JavaScript Functions to Boost Performance  8   To implement debouncing, we write a debounce function that takes a function and a delay. It clears any existing scheduled call and schedules a new one to run after the given delay. If the event keeps firing, the previous schedule is canceled and replaced, which means the wrapped function only runs after the events have paused for the delay.
function debounce(fn, delay) {
  let timeoutId;

  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}
  How to Debounce JavaScript Functions to Boost Performance  12  

Steps

Create a function that you want to control, such as reportNewWidth.   How to Debounce JavaScript Functions to Boost Performance  1   Create a debounce function that accepts the function and a delay.   How to Debounce JavaScript Functions to Boost Performance  9   Inside debounce, keep a timeout id, clear it on every call, and set a new timeout.   How to Debounce JavaScript Functions to Boost Performance  10   When the timeout completes, call the original function with the saved arguments and the original this context.   How to Debounce JavaScript Functions to Boost Performance  11  

Applying JavaScript Function Debouncing to window resize

  How to Debounce JavaScript Functions to Boost Performance  13   Now we take the function on the top and use debouncing in the resize listener. Instead of calling the function directly in the event, we pass it through debounce and provide a delay. Let us say the delay time is 500 milliseconds, which is 0.5 second.   How to Debounce JavaScript Functions to Boost Performance  15  
function reportNewWidth() {
  console.log("New width is:", window.innerWidth);
}

function debounce(fn, delay) {
  let timeoutId;

  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

window.addEventListener("resize", debounce(reportNewWidth, 500));
  How to Debounce JavaScript Functions to Boost Performance  14   If you resize the window with this in place, you will get the result slowly rather than getting dozens of logs every second. At every time when the 0.5 second completes after the last resize event, it gives the result and executes the function again. This is what debouncing is. This is the main code by which we do the debouncing, and this is the simple method by passing the function and the time of delay inside the debounce function.   How to Debounce JavaScript Functions to Boost Performance  16  

Final thoughts

Debouncing waits for rapid events to settle before running your code. The _window.resize_ example makes it clear why this matters for performance and readability. Wrap your heavy or frequent handlers with a small _debounce_ helper and pass a sensible delay like 300 to 500 milliseconds to avoid unnecessary work.

Leave a Comment