Debounce function – JavaScript/FrontEnd interview questions

JavaScript or FrontEnd interviews be tricky sometimes. These questions aim at testing your understanding of JavaScript concepts like – hoisting, closures, prototypes and so on. We will discuss a debounce function in this post. Debounce function

Debounce is used to limit the execution of a function. For example, if a user is typing something on an input and for each letter which user type, we want to auto-complete that search. The trick here is that we don’t want to make an API call on every keystroke, instead limit that based on some parameters. We want to write a function which executes after n seconds of a user pressing a keystroke. If a user presses a keystroke before then wait for another n seconds and then get results for that auto-complete. This functionality is called debounce function.

Lodash and many other JS utility libraries have advanced debounce functions – Lodash Debounce

A simple debounce function

  • has 3 input params – function, time and immediate.
  • function is the actual function which debounce executes after a timeout.
  • time is the time in milliseconds after which the given function needs to be executed.
  • immediate act as a flag, if passed as truthy we will execute function immediately.

Whenever a call is made to debounce function we will execute that function in setTimeout and if next call is made then cancel the previous setTimeout and start next setTimeout. If immediate flag is passed then do not wait and execute the function.

Also, attach this to browser window onResize so that it can be executed everytime the window is resized. But debounce will make sure that it cancels previous calls if next resize is done within n seconds.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *