Rifat Nabi

Jul 20, 2013

Detect end of jQuery Resize event using underscore's debounce

I'm a big fan of UnderscoreJS. You 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 you with a lot of useful utilities. I have planed to post a few of them with some real life use cases.

Problem

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

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

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

Live Demo

Then when you resize your window by dragging. It will execute several times. And, if the function has some heavy operations then it can crash the browser. You will also notice a CPU spike.

Solution

You 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 you can rewrite your code as-

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

Live Demo

500 milliseconds wait pretty much works for me very well. But, you can tinker with this to get the result you 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