Back to all questions

What is Debounce?

Devs Hive

Devs Hive

Seen on interview: 4 users

Debounce is a very common technique that delays the execution of a function until an event has stopped firing for a certain amount of time. The simplest example of its use is a search field. Imagine input where the user can type a search query. By default, every change of the value triggers an event that sends a search request to the backend.

Imagine you are searching for the name Alex

// По замовчуванню ми відправимо 4 послідовних запита, на кожну зміну input

/**
* https://my-api.com?name=A
* https://my-api.com?name=Al
* https://my-api.com?name=Ale
* https://my-api.com?name=Alex
* */

This gives us 2 problems:

  1. Inefficient use of resources - with many users, this can potentially overload the backend
  2. Race condition - name=A has lower selectivity than name=Alex, so in theory name=A may finish later and the user will see a completely different response from the one they expected.

Using the Debounce technique, we can send requests not on every change of input, but, for example, 300 milliseconds after the user has stopped typing. This way, we send only one request with the latest changes.

// Ігноруємо, бо користувач друкує

/**
* A
* Al
* Ale
* Alex
* */


// Користувач перестав друкувати
// Якщо в рамках 300 мілісекунд він не друкує, відправляємо запит на пошук
// https://my-api.com?name=Alex

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!