Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.