When typing into a search input, there is a delay before the typeahead results
appear. This functionality is controlled by a function called debounce()
.
The debounce()
function delays processing of keyup
event (events in general)
until the user stopped typing for a specified amount of time.
It prevents UI code from needing to process every event and also reduces number of API calls sent to server. Hence, it improves performance as it does not process every character as it's entered.
const debounce = (callback, delay) => {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout( () => {
callback.apply(context, args);
}, delay);
}
}
- The wrapper function takes in two arguments: a callback and delay for timeout which will hold state of the timeout.
- timeout variable will be undefined until the timeout is set in returned function.
- Return function will be called everytime the function is called. NOTE this cannot be arrow function as context is not preserved.
- clearTimeout if timeout exists.
- setTimeout and pass the applied function.