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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
var debounce = function(fn, time, immediate) { var timeout; return function() { var that = this; var args = arguments; var later = function() { if(!immediate){ timeout = null; fn.call(that, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, time); if(callNow) { fn.call(that, args); } }; } window.onresize = debounce(resize, 3000); function resize(e) { console.log('height', window.innerHeight); console.log('width', window.innerWidth); } |