First Principles
Programming

Debouncing in Javascript

Debouncing delays a function until the activity stops — fewer API calls, smoother UI. How it works, with a search example.

By Fadjar Rafi. Published 21 Oct 2025. 2 min read.

Contents
  1. What is debouncing
  2. The debounce function

Debouncing is a technique for delaying a function until a burst of activity settles down. It's a small trick that makes an app feel smoother and cuts a lot of wasted work.

What is debouncing#

The idea is simple: instead of running a function on every event, you wait until the events stop for a set amount of time, then run it once.

Typing into a search box is the classic case. You don't want to fire a request on every keystroke — that makes the UI feel laggy and hammers your API. Instead, you wait until the user pauses, then send a single request with what they typed.

Keystrokes reset the timer; the API call fires once after typing stops

The debounce function#

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

Each call clears the timer from the previous one with clearTimeout() and starts a fresh timer. So func only runs once no new call has come in for the full delay.

Now say we have a search function:

async function searchAPI(query) {
  try {
    const response = await fetch(`/api/search?q=${query}`)
    const results = await response.json()
    displayResults(results)
  } catch (error) {
    console.error('Error:', error)
  }
}

Wire it up without debouncing, and it fires on every single keystroke:

// without debouncing — one API call per keystroke
document.getElementById('search').addEventListener('input', (e) => {
  searchAPI(e.target.value)
})

// "a" → call
// "app" → call
// "appl" → call
// "apple" → call

Wrap the handler in debounce() and it waits for the pause — one call instead of four:

// with debouncing — one API call after the user stops typing
document.getElementById('search').addEventListener(
  'input',
  debounce((e) => searchAPI(e.target.value), 300)
)

// "apple" → call

Same behavior for the user, a fraction of the requests.