Skip to main content

Command Palette

Search for a command to run...

Implement Debounce and Throttle in JavaScript

Updated
2 min read
Implement Debounce and Throttle in JavaScript

When building interactive web applications, performance often becomes a concern—especially when dealing with events that fire frequently, like scrolling, resizing, or key presses. Without control, these event handlers can overwhelm the browser and APIs. This is where debounce and throttle come in: two powerful techniques to control how often a function executes.

Why Use Debounce and Throttle

  • Debounce: Ensures a function only runs after a specified delay from the last time it was called. Ideal for search boxes, window resizing, or form validation, where you don't want to query the server on every keystroke—only after the user stops typing.

  • Throttle: Ensures a function runs at most once in a set time interval. Perfect for scroll and resize events, where you want smooth updates without overwhelming the browser or APIs.

Debounce Implementation

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

const test = (text) => console.log(text);
const debounceTest = debounce(test, 10000);

debounceTest("Hello, World!");
// this call cancles the first timer
// "Hello, World! 2" is logged after 15 seconds
setTimeout(() => debounceTest("Hello, World! 2"), 5000);

Throttle Implementation

function throttle(func, limit) {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

const test = (text) => console.log(text);
const throttledTest = throttle(test, 10000);

//only the first one is logged
throttledTest("Hello, World! One and only.");
throttledTest("Hello, World! 2");
throttledTest("Hello, World! 3");

// call again after the throttle time
setTimeout(() => {
  //the first one is logged
  throttledTest("Hello, World! Again");
  throttledTest("Hello, World! 2");
}, 15000);

More from this blog

UI Dev

18 posts