Skip to content

Instantly share code, notes, and snippets.

@frankie9793
Last active July 14, 2019 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankie9793/8057b01c7cde3021fc930052ecd82057 to your computer and use it in GitHub Desktop.
Save frankie9793/8057b01c7cde3021fc930052ecd82057 to your computer and use it in GitHub Desktop.
JavaScript Debouncer

Javascript Debouncer

Context

When typing into a search input, there is a delay before the typeahead results appear. This functionality is controlled by a function called debounce().

Funtionality

The debounce() function delays processing of keyup event (events in general) until the user stopped typing for a specified amount of time.

Outcomes

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.

Implementation

const debounce = (callback, delay) => {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout( () => {
           callback.apply(context, args);
        }, delay);
     }
}
  1. The wrapper function takes in two arguments: a callback and delay for timeout which will hold state of the timeout.
  2. timeout variable will be undefined until the timeout is set in returned function.
  3. Return function will be called everytime the function is called. NOTE this cannot be arrow function as context is not preserved.
  4. clearTimeout if timeout exists.
  5. setTimeout and pass the applied function.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment