A common interview question that is asked during frontend interviews is to write a JavaScript debounce function polyfill. I have been asked this question and I too have asked this question while taking interviews. So, if you are preparing for frontend interviews then Javascript debounce function polyfill is a must for you.

Before we dig into the technical implementation of debounce function lets first understand what debounce function is and where its used. This will help us in understanding the working of the code in a better way.

What is debounce function in JavaScript

Debounce function improves the performance of an application by limiting the rate at which a given function executes. You pass a timeout value X to debouce function and it waits for X milliseconds before executing the function. If the function is called before X milliseconds then the timeout is reset again.

Debouce is a higher order function which returns another function (let’s call it executedFunction) which can be called by any event handler. This executedFunction will be called by the event handler continuously but it will make sure that the original function is executed in a rate limited manner after X milliseconds.

Let’s take an example: Suppose you are working on an autocomplete feature where you need to make an API call to fetch results on user text box inputs.

  • Once approach can be to fetch results as soon as user enters in the textbox. But this approach is not optimized as you will end up making N API calls for N characters entered by user.
  • Another approach can be to use debounce function and attach executedFunction with the textbox input change event. The executedFunction will make sure that API call is called X millioseconds after the user has stopped entering into the textbox. This will drastically reduce the API calls made.

Lets code Javascript Debounce Function Polyfill

Now, since we know about what Debounce function does and where its best used lets try to write a polyfill for it.

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// X milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  let timeout;

  return function executedFunction(...args) {
    const context = this;

    const later = () => {
      clearTimeout(timeout);
      timeout = null;
      if(!immediate) func.apply(context, args);
    }

    const executeImmediately = immediate && !timeout;

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if(executeImmediately) func.apply(context, args);
  }
}

To understand the working of the debounce function lets take an example. In the code below we have create a function which shows an alert box and we have debounced it with a wait of 2 seconds. Then we have attached this debounced function to the windows scroll handler. Now, when you start scrolling, but as soon as you stop within two seconds you see an alert box.

const showAlert = () => {
  alert("JS Rocks");
}

const debouncedFunction = debounce(showAlert, 2000);

window.addEventListener('scroll', debouncedFunction)

Javascript Debounce function polyfill is widely asked in interviews so having an idea of its working is a must have for every frontend developer. Please go through the code and explanation above. If you have any query then please reach out to via comments.