function debounce

My Favorite Functions and Patterns: debounce

This is the fourth post on my favorite functions and patterns in functional programming. Thank you for joining me! There is more to come. And if this is your first visit, please have a look at the Index for the rest of the collection. Today, I’m sharing the function debounce.

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, they 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

We're building an AI-powered Product Operations Cloud, leveraging AI in almost every aspect of the software delivery lifecycle. Want to test drive it with us? Join the ProdOps party at ProdOps.ai.