Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Debouncing in javascript✨
Aishanii
Aishanii

Posted on

     

Debouncing in javascript✨

To optimise browser performance as well as keep up with user experience deliverables, there are few techniques, one of which isdebouncing.

A very fine example for this would be any search bar. When you type a word in search bar with every letter it shows new recommendations.

From the surface the trick here must be making anAPI call every time somebody enters a letter to fetch desirable options according to latest input.

A better way to do this is through debouncing,

  • We set athreshold for a time period, can be 5s or .05 sec.

  • Every time this threshold timer expires, we make an API call to get data best matching the input.

  • Clear the timer and reset

Code:

<inputclassName="search-bar"onChange={hecticSearchHandler}/>
Enter fullscreen modeExit fullscreen mode
functionhecticSearchHandler(...args){/* capture the search query entered by customer */const{value}=args[0].target;/* Make an API call with search query */getSearchResults(value);}
Enter fullscreen modeExit fullscreen mode

Image description

Reusable function code:

constoptiSearchHandler=debounceFunc(searchHandler,500)constdebounceFunc=(func,delay)=>{lettimer;returnfunction(...args){constcontext=this;clearTimeOut(timer);timer=setTimeOut(()=>{func.apply(context,args);},delay)}}
Enter fullscreen modeExit fullscreen mode

Watch this video for clarity:Debounce interview ques

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
brense profile image
Rense Bakker
I am a fullstack developer with experience designing and building responsive web apps. Proficient with ReactJS, Typescript, Javascript, HTML and CSS.
  • Joined

In React 18 you do not have to debounce anymore unless you really only want something to happen after a very specific amount of time. Otherwise you can use the newuseDeferredValue hook:reactjs.org/blog/2022/03/29/react-...

CollapseExpand
 
aishanipach profile image
Aishanii
I journal tech learnings and may give my 2 cents💁‍♀️ | Follow my System design journey!

Sounds interesting.
Will definitely check this out!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I journal tech learnings and may give my 2 cents💁‍♀️ | Follow my System design journey!
  • Location
    India
  • Joined

More fromAishanii

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp