← homeProgramming (Програмування)

What is debounce in JavaScript and why is it important?

Debounce in JavaScript is a technique that limits the frequency of function calls to avoid unnecessary load on the browser or server. Learn how debounce works.

Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
If you have ever worked with events in JavaScript, such as scroll, resize, or keyup, you have probably noticed that they can be triggered very frequently. For example, when typing in a search field, the keyup event can fire after each key press. This can create unnecessary load on the browser or server, especially if each call makes an API request.
To avoid such problems, debounce is used — a technique that limits the frequency of function calls by delaying its execution until the event stops repeating for a specified amount of time.

How does debounce work?

The idea is simple: when the event is triggered, we postpone the execution of the function for a certain period of time. If the event is triggered again before this time is up, the timer is reset and the countdown starts over. Only when the event stops does the function execute.

Debounce example in JavaScript

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

// Using debounce to handle text input event
const input = document.querySelector("#search");
const handleInput = (event) => {
  console.log("Search: ", event.target.value);
};

input.addEventListener("keyup", debounce(handleInput, 500));
In this example, each input in the search field resets the timer, and only after 500ms without new input does handleInput execute.

Where to use debounce?

  • Search queries — to avoid sending requests to the server on every key press.
  • Window resize handling — to avoid overloading the browser with calculations.
  • Scroll event listeners — for example, to load new content while scrolling (infinite scroll).
  • Auto-saving forms — to save data only after input is finished.
  • Form validation - for example, to check for an available username.
Debounce helps optimize performance by reducing the number of function calls that are triggered frequently. This is especially useful when working with frequent events such as text input, scrolling, or window resizing. By using debounce, you can improve user interaction and reduce system load.

🔥 More posts

All posts
What is CFB (Cipher Feedback)?
Programming (Програмування)Mar 21, '25 16:53

What is CFB (Cipher Feedback)?

CFB (Cipher Feedback) is an encryption mode where each block depends on the previous one, providi...

What is XOR and how does it work?
Programming (Програмування)Mar 21, '25 17:05

What is XOR and how does it work?

XOR (exclusive OR) is a logical operation used in encryption, bit manipulation, and difference ch...