mikemaccana mikemaccana - 8 days ago 6
Javascript Question

What does _.debounce do?

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 means, already knows what debounce means.

What does debounce actually do?

Answer

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.