Menu

Debounce in JavaScript: The 10-Line Fix That Stops Your Search Box Firing on Every Keystroke
πŸ“°

Debounce in JavaScript: The 10-Line Fix That Stops Your Search Box Firing on Every Keystroke

DEV Community: webdevΒ·Raja HunainΒ·9 days ago
#4IJ7Jf8p
#devtowebdev#devto#dev#search#function
Long article (607 words) β€” no AI summary yet.
Reading 0:00
15s threshold

Type "javascript" into a search box and your code fires an input event for every letter. If the handler calls an API each time, that is ten requests for one word β€” nine of them for queries nobody will ever see. On a slow connection the answers can even arrive out of order, so the list shows results for "jav" under the finished word "javascript".

The fix is called debouncing: wait until the user stops typing, then run once. The whole technique is about ten lines.

The function

function debounce ( fn , wait ) { let timeoutId ;

return function ( . . . args ) { clearTimeout ( timeoutId ) ; timeoutId = setTimeout ( ( ) => { fn . apply ( this , args ) ; } , wait ) ; } ; }

Enter fullscreen mode

Exit fullscreen mode

It is a higher-order function. It takes your function and a delay, and returns a new function that is the debounced version. Every call cancels the pending timer and starts a fresh one, so only the last call in a burst survives.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.