Skip to content

Instantly share code, notes, and snippets.

@jmlivingston
Forked from nmsdvid/new_gist_file.js
Last active March 9, 2020 17:29
Show Gist options
  • Save jmlivingston/1c8ad636bc0b8b810cbedabf2ac72b15 to your computer and use it in GitHub Desktop.
Save jmlivingston/1c8ad636bc0b8b810cbedabf2ac72b15 to your computer and use it in GitHub Desktop.
Simple JavaScript Debounce Function

Definition

Prevents function from being called until delay has passed without being called. This prevents excessive computer operations like API calls or heavy calculations.

Pattern

Curried function with two parameters: function and delay. As long as the debounced function continues to be called within the delay, the original function will not be called.

Use Cases

  • search field (onkeyup event)
  • auto-complete (onkeyup event)
  • getting scroll position (onscroll event)
  • resizing of window (onresize event)

Code

const debounce = (callback, delay = 250) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      timeoutId = null
      callback(...args)
    }, delay)
  }
}

Test

Debounced function is called 10 times, but original greet function fires once as expected.

const greet = name => console.log(`Hello ${name}!`)
const debouncedGreet = debounce(greet, 3000)

for (let i = 0; i < 10; i++) {
  debouncedGreet(`${i}`)
}

// Hello 9!

Notes

It's also worth checking out lodash's code for debounce and documentation. It's more verbose, but also more optimal as it includes leading and trailing flags like @anurbol's second example above. Just be sure to never import all of lodash due to it's size and import it like this instead: import _debounce from 'lodash/debounce'. I like prefixing with an underscore in case I need to analyze, refactor, or remove any lodash references later. Alternatively, you can just npm install lodash.debounce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment