Skip to content

Implement debounce

Daisho Komiyama edited this page Feb 19, 2022 · 1 revision

Imagine you write a search functionality that sends the user's input to the server then the server returns the result.

If the user types,

p

We make a GET request with the search term p then the user types i,

pi

We, again, make a GET request with the search term pi then the user types z,

piz

We, again, make a GET request with the search term piz...

We can't do this for each input as we'll end up making tons of requests within a second. That burns our server, and you'll get paged! 😩

debounce function

Let's write our debounce function.

// definition
function debounce(fn, time) {
  let timeoutId

  return function() {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }

    timeoutId = setTimeout(() => {
      fn.apply(this, arguments)
    }, time)
  }
}

// usage
const d = debounce(() => console.log('sending request!'), 500)
d()
d()
d()
d() // sending request!

So if the user types p then types the next character i within 500ms, the console.log passed to debounce runs only for the last call.

Clone this wiki locally