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.β¦