For the love of art

Bensalem artist Joanna Krasnansky displays scenic watercolor exhibit at the Bucks County Visitor Center It’s easy to get lost (both mentally and physically) among the walls of paintings in Joanna…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




How to debounce in Javascript?

Debounce is a technique that ensures that a function in your web application is not called too frequently which in turn optimises the performance of your application.

Example: There is a search box that invokes a function and makes a call to the server on every keystroke

Search functionality without debounce

You can see in the above image that API request happens for every letter even though we are interested in the result of the last request.

Following in the current implementation of our search box handler:

So we have an opportunity to reduce the number of calls here. To do that we will be writing a debounce function.

A debounce function is function that takes input an original function that executes our logic and number of milli seconds say wait. Debounce function will ensure that our original function is not called until wait milli seconds have been passed since its last call.

Below is the simple implementation of a debounce function

So our implementation of handleSearch becomes

Results?

Search functionality with debounce

You can see in the above image that with debounce API request is only made once.

You don’t always have to write a a debouce implementation. If your code base uses libraries like lodash, underscore.js, they provide debounce function with additional options.

Add a comment

Related posts:

Take a Hike

As we wandered up the lovely residential area of suburban Whittier, I noticed so many things. Every dog we passed was pint-sized, the trees varied from palm trees to oak trees, most lawns had…

The wonderful life of Ellen blonde

Ellen blondeis a famous American talk show host and comedian. She is the only host in history to host the Oscars, Grammy Awards and Emmy Awards. Forbes ranked 23rd on the 2010 Forbes list of the top…

Newspapers In Gasconade County

This was a Hermann publication. The only notable articles other than the typical obituaries and property sales were articles about Mormonism. The entire article is in German, but it was published in…