Rifat Nabi

Jul 20, 2013

Detect end of jQuery Resize event using underscore's debounce

I'm a big fan of UnderscoreJS. We can do amazing things with it.

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux, and Backbone.js's suspenders.

It provides us with a lot of useful utilities. I have planed to post a few of them with some real life use cases.

Problem

jQuery has a few events (resize, scroll, touchmove, mousemove, etc), which keep firing during the whole event lifespan. But, most of the time we want to do something when it is finished.

Let's consider the window resize event as an example. There are times when we want to resize our application layout or the height of a div when this event occurs. Normally if we just use something like this-

$(window).resize(function(){
    // Do our things here
});

Live Demo

Then when we will be resizing the window by dragging. It will be executed several times. And, if the function has some heavy operations then it can even crash the browser. You will also notice a CPU spike.

Solution

We can use underscore's debounce function to get rid of that problem. But, first let's check the signature of this function.

_.debounce(function, wait, [immediate])

And, what is does (from the official documentation)

Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked

So, now we can rewrite our code as-

$(window).resize(_.debounce(function(){
    // Do our things here
}, 500));

Live Demo

500 milliseconds wait pretty much works for me very well. But, we can tinker with this to get the result we want.

debounce has a third optional parameter immediate, which is false by default. But I will not discuss it today. Let's leave it for another day.

comments powered by Disqus