Skip to content

Debounce in Javascript

Posted on:April 10, 2023 at 03:22 PM

Learn how to create a simple debounce utility in javascript

Table of contents

Open Table of contents

Debounce code snippet

// debounce.js
function debounce(functionToDebounce, durationInMs) {
  let timeoutId = null;

  return (...args) => {
    window.clearTimeout(timeoutId);
    timeoutId = window.setTimeout(() => {
      functionToDebounce.apply(null, args);
    }, durationInMs);
  };
}

Explanation

Here debounce function takes two parameters ( a function to debounce and duration for debouncing). timeoutId stores the reference to remove stale queued calls.

We return a function from debounce , so debounce is high order function. High order function is a function that takes and/or returns one or more functions. This returned function when called firstly clears stale queued calls via clearTimeout and then queue a new call via setTimeout.

clearTimeout won’t complain even if timeoutId is falsy and the value of timeoutId is remembered via closure.

Inside the setTimeout we call the original function to be debouned via apply and pass all the arguments needed.

Check out the codesandbox link https://codesandbox.io/s/debounce-in-javascript-gfomon