Debouncing and Throttling Explained Through Examples

The following is a guest post by David Corbacho, a front end engineer in London. We’ve broached this topic before, but this time, David is going to drive the concepts home through interactive demos that make things very clear.

Debounce and throttle are two similar (but different!) techniques to control how many times we allow a function to be executed over time.

Having a debounced or throttled version of our function is especially useful when we are attaching the function to a DOM event. Why? Because we are giving ourselves a layer of control between the event and the execution of the function. Remember, we don’t control how often those DOM events are going to be emitted. It can vary.

When scrolling using a trackpad, scroll wheel, or just by dragging a scrollbar can trigger easily 30 events per second. But scrolling slowly (swapping) in a smartphone could trigger as much as 100 events per second during my tests. Is your scroll handler prepared for this rate of execution?

In 2011, an issue popped up on the Twitter website: when you were scrolling down your Twitter feed, it became slow and unresponsive. John Resig published a blog post about the problem where it was explained how bad of an idea it is to directly attach expensive functions to the scroll event.

The suggested solution by John (at that time, five years ago) was a loop running every 250ms, outside of the onScroll event. That way the handler is not coupled to the event. With this simple technique, we can avoid ruining the user experience.

These days there are slightly more sophisticated ways of handling events. Let me introduce you to Debounce, Throttle, and requestAnimationFrame. We’ll also look at the matching use cases.

Debounce

The Debounce technique allow us to “group” multiple sequential calls in a single one.

Imagine you are in an elevator. The doors begin to close, and suddenly another person tries to get on. The elevator doesn’t begin its function to change floors, the doors open again. Now it happens again with another person. The elevator is delaying its function (moving floors), but optimizing its resources.

You can see how sequential fast events are represented by a single debounced event. But if the events are triggered with big gaps, the debouncing doesn’t happen.

Leading edge (or “immediate”)

You may find it irritating that the debouncing event waits before triggering the function execution, until the events stop happening so rapidly. Why not trigger the function execution immediately, so it behaves exactly as the original non-debounced handler? But not fire again until there is a pause in the rapid calls.

Debounce Implementations

The first time I saw debounce implemented in JavaScript was in 2009 in this John Hann post (who also coined the term).

Soon after that, Ben Alman created a jQuery plugin (no longer maintained), and a year after, Jeremy Ashkenas added it to underscore.js. It was later added to Lodash, a drop-in alternative to underscore.

The 3 implementations are a bit different internally, but their interface is almost identical.

There was a time that underscore adopted the debounce/throttle implementation from Lodash, after I discovered a bug in the _.debounce function in 2013. Since then, both implementations have grown apart.

Lodash has added more features to its _.debounce and _.throttle functions. The original immediate flag was replaced with leading and trailing options. You can choose one, or both. By default, only the trailing edge is enabled.

The new maxWait option (only in Lodash at the moment) is not covered in this article but it can be very useful. Actually, the throttle function is defined using _.debounce with maxWait, as you see in the lodash source code.

Debounce Examples

Resize Example

When resizing a (desktop) browser window, they can emit many resize events while dragging the resize handle.

A similar use case would be to wait until user stops typing before validate its input. “Your password is too short” type of messages.

How to use debounce and throttle and common pitfalls

It can be tempting to build your own debounce/throttle function, or copy it from some random blog post. My recommendation is to use underscore or Lodash directly. If you only need the _.debounce and _.throttle functions, you can use Lodash custom builder to output a custom 2KB minified library. Build it with this simple command:

Throttle

By using _.throttle, we don’t allow to our function to execute more than once every X milliseconds.

The main difference between this and debouncing is that throttle guarantees the execution of the function regularly, at least every X milliseconds.

The same way than debounce, throttle technique is covered by Ben’s plugin, underscore.js and lodash.

Throttling Examples

Infinite scrolling

A quite common example. The user is scrolling down your infinite-scrolling page. You need to check how far from the bottom the user is. If the user is near the bottom, we should request via Ajax more content and append it to the page.

Here our beloved _.debounce wouldn’t be helpful. It only would trigger only when the user stops scrolling.. and we need to start fetching the content before the user reaches the bottom.
With _.throttle we can warranty that we are checking constantly how far we are from the bottom.

Cons

If the browser tab is not active, it would not execute. Although for scroll, mouse or keyboard events this doesn’t matter.

Although all modern browsers offer rAF, still is not supported in IE9, Opera Mini and old Android. (A polyfill)[http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/] would be needed still today.

rAF is not supported in node.js, so you can’t use it on the server to throttle filesystem events.

As a rule of thumb, I would use requestAnimationFrame if your JavaScript function is “painting” or animating directly properties, use it at everything that involves re-calculating element positions.

To make Ajax requests, or deciding if adding/removing a class (that could trigger a CSS animation), I would consider _.debounce or _.throttle, where you can set up lower executing rates (200ms for example, instead of 16ms)

If you think that rAF could be implemented inside underscore or lodash, they both have rejected the idea, since it’s a specialized use case, and it’s easy enough to be called directly.

Examples of rAF

I will cover only this example to use requestAnimation frame on scroll, inspired by Paul Lewis article, where he explains step-by-step the logic of this example.

I put it side by side to compare it to _.throttle at 16ms. Giving similar performance, but probably rAF will give you better results on more complex scenarios.