Day 29 / 100

Today learning tip!
Debounce in Javascript

The debounce function delays the processing of the event until the user has stopped typing for a predetermined amount of time.

Have you noticed the difference below?👇

(1/6)

#100daysofcode via @100daysofcodes
Have you noticed that when you type into a search input, there will be a delay before the typeahead results appear?

This functionality is frequently controlled by a function called a debounce (it could also be a throttle function that has a similar outcome).

(2/6)
This prevents your UI code from needing to process every event and also drastically reduces the number of API calls sent to your server.

Processing every character as it’s entered could harm performance and add unnecessary load to your backend.

(3/6)
A debounce is a cousin of the throttle, and they both improve the performance of web apps.

But, used in different cases. A debounce is utilized when you only care about the final state.

For eg, waiting until a user stops typing to fetch typeahead search results.

(4/6)
A throttle is best used when you want to handle all intermediate states but at a controlled rate.

For eg, track the screen width as a user resizes the window and rearrange page content while it changes instead of waiting until the user has finished.

(5/6)
A debounce is a higher-order function, which is a function that returns another function.

Common scenarios for a debounce are Resize, Scroll, Keyup/keydown events.

In addition, consider any interaction that triggers excessive calculations or API calls with a debounce.

(6/6)
You can follow @code_rams.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: