Skip to content

WPShout Newsletter

Sign up for news, tips, and insights to help you build better websites.

Newsletter - Top banner

JavaScript Debounce Function Explained (Code Example)

When working with events in JavaScript, things can get messy if they fire too quickly. Imagine someone typing in a search box, or you dragging the corner of your browser window. Those events can fire dozens of times per second. Without a safeguard, your app might slow down or waste resources.

That’s where debouncing comes in. A debounce function delays the execution of an event handler until the activity stops for a set period of time. In other words, no matter how many times the event fires, the callback only runs once the dust has settled.

When listening for events or actions on a page that may occur in rapid-fire succession, a JavaScript debounce function is a common solution. This improves performance and prevents the browser from slowing down or freezing.

When to Use a Debounce Function

Debouncing is useful whenever events fire too quickly and risk slowing down or overwhelming your app. Common use cases include:

  • Running search queries as a user types (so you don’t spam your API with every keystroke)
  • Handling window resize events (to avoid recalculating layouts on every pixel change)
  • Autocomplete suggestions
  • Scroll listeners (e.g., lazy loading content)

Example: Debouncing a Resize Event

Below is an example that expects the window to be resized but delays the end result. This will ensure multiple window resize events don’t trigger the results too often. The result in this case is printing the window width to the console, but in the context of a real application this could be something more resource-intensive.

let doResizeResult = () => {
  console.log(window.innerWidth);
}

let debounce = (callback, delay) => {
  let myTimeout;
  return () => {
    clearTimeout(myTimeout);
    myTimeout = setTimeout(() => {
      callback()
    }, delay);
  };
};

let doDebounce = debounce(() => doResizeResult(), 1000)

window.addEventListener('resize', () => doDebounce());


Code language: JavaScript (javascript)

👉 Try it in this CodePen demo. Resize the window quickly, and you’ll see that only the last action is logged once you stop dragging.

Note: To the best of our knowledge, the information above and the snippet are accurate and up to date. However, in case you notice something wrong, please report snippet or leave a comment below.

View All Code Snippets
Louis Lazaris
Share:

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!