Throttling and debouncing are arguably two concepts too often overlooked in front end development, even though they’re quite simple to grasp and bring major benefits when developing complex and/or intensive web applications.
Theory
Throttling and debouncing function calls basically prevent functions to be executed too many times in a specified time interval. More specifically:
- Throttle will queue and execute functions calls at most once per given milliseconds;
- Debounce will execute the function once and filter all following calls until a given time has passed, then fire it again.
If you’re more a visual person, check out this interactive example to get how they work.
Ok, but when should I use them?
Throttling and debouncing are particularly useful when you need to listen (and react) to events that fire a lot of times, rapidly – think of a window resize, or a page scroll. If you try to attach a console.log() handler to one of those two events and fire them, you might have something like that:
That’s a lot of logs, right? Imagine if our handler function had to calculate different elements’ positions and had to move stuff around at the same time. Now, put this in the context of a heavy-interactive web application and your lag is served!
Enter throttle and debounce
That’s a perfect use case for some good ol’ throttling.
The most famous implementation of the two is probably the Underscore.js one, which we’re going to use in our small example.
Its syntax is quite simple (from the Underscore.js docs):
_.throttle(function, wait, [options])
Let’s put it in practice!
A _.throttle example
Our console.log() handler could be like this:
var i = 0;
var handler = function() {
console.log('Scroll event fired ' + i + ' times!');
i++;
}
We’ll pass it as an argument to the _.throttle function, so that it will return our new, throttled handler:
var throttledHandler = _.throttle(handler, 500);
Now, some jQuery sugar to listen for the scroll event and fire it:
$(window).on('scroll', throttledHandler);
Et voilà, less lag and a better approach to intensive Javascript application development:
You can see how our throttled handler function now fires at most once every 500ms.
If you’re interested in how throttling and debouncing work internally, take a look at the annotated source code provided by the Underscore.js pals!
Leave a Reply