A project I've been working on uses _.debounce().
The Underscore JS documentation for debounce reads as follows:
debounce
_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.
This obviously assumes that anyone who wants to know what debounce()
does, already knows what 'debounce' means.
What does debounce actually do?
Description from the source code of underscore.js:
Code it self:
It holds execution of a function until a timeout is expired. This is to avoid continuous execution of functions when not needed. Beware, since underscore.debounce() relies on complex code. Most of times, a simple "if" statement inside the function is much faster than debounce. You can implement a counter, executing method only each N of iterations, or a timeout, checking that at least a certain amount of milliseconds elapsed.
I wrote a post titled Demystifying Debounce in JavaScript where I explain exactly how a debounce function works and include a demo.
A debounce function provides a way to "throttle" a function's execution. They are typically used in circumstances where a function is bound to an event that fires in rapid succession. It is common to see a debounce function being used on window resizes and scrolls.
Whether Underscores or another JavaScript library, all debounce functions are built on JavaScript's native
setTimeout
method. So, before you dive into understanding what a debounce function does, it's a good idea to have a thorough understanding ofWindowTimers
(links to MDN).Additionally, you'll want to have a good understanding of scope and closures. Although relatively small in size, debounce functions actually employ some pretty advanced JavaScript concepts!
With that said, below is the basic debounce function explained and demoed in my post referenced above.
The finished product
The explanation
Basically it throttles calls so if it is called more than once in a short period of time, only one instance will be called.
Why would you use it?
Events like window.onresize fire multiple times in rapid succession. If you need to do a lot of calculations on the new position, you would not want to fire the calculations multiple times. You only want to fire it when the user has finished the resizing event.