Skip to content

Instantly share code, notes, and snippets.

@jmilamwalters
Last active December 11, 2018 19:24
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 jmilamwalters/0bacc73d79c3a43c2cea7fdb63b65946 to your computer and use it in GitHub Desktop.
Save jmilamwalters/0bacc73d79c3a43c2cea7fdb63b65946 to your computer and use it in GitHub Desktop.
Functions: `debouce`

Functions: debounce

A compilation of my favorite functions and patterns in functional programming

I first learned of debounce from something of a mentor, who explained that it originates from the early days of the Internet when it was important to preclude repeated clicks to Buy Now buttons.

Generally speaking, to debounce a function is to nullify subsequent calls -- for an allotted period of time -- following the function's initial invocation. Debouncing presides as something of a governor over your function, and can be made to consolidate sequences of function calls into one.

In many contexts, its use is straightforward:

import {debounce} from 'lodash'

function submitPayment() { 
  // Process money...
}

// Invoke `submitPayment()` when clicked, debouncing subsequent calls for no
// fewer than 5 seconds.
function onClick() {
  return debounce(submitPayment, 5000, { leading: true, trailing: false })
}

With options of leading set to true and trailing false, we enable firing of submitPayment() at the onset. Should the user click Buy Now, she will be unable to fire off its associated action until at least five seconds have passed since the previous click. Such distinguishes debouncing from throttling, and there is no shortage of lengthy discussions on the differences.

Debouncing can be useful for consolidating a variety of expensive or precarious calculations; I find it especially pertinent in front-end development:

  • Resize events on windows
  • Costly scroll events
  • Ajax requests resulting from onblur events

Further reading

Resources

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