Julian Jelfs’ Blog

jQuery plug-in for deferred resize (or anything)

Posted in Javascript, jQuery by julianjelfs on May 7, 2010

There are a class of UI events that fire many many times in quick succession. Things like mouse move, resize or even keyup. Often (in my experience) you might want to perform some action after the event has stopped happening rather than for each and every event. Suppose you want to do some expensive re-organisation of the UI in response to the resizing of some container element then you most likely don’t want to do this in response to every resize event, rather you want to wait until it appears that the user has stopped resizing and then perform the action. I have found it useful to encapsulate this pattern as a jQuery plug-in so that instead of this:

element.resize(function(){
    //do something expensive
});

I can do this:

element.deferredResize(function(){
    //do something expensive
}, 300);

And the plug-in looks like this:

$.fn.extend({    
    deferredResize : function(fn, delay){
        var timer = null;
        $(this).resize(function(){
            if(timer != null){
                clearTimeout(timer);
                timer = null;
            }
            timer = setTimeout(fn, delay);
        });
        return this;
    }
});

So when it picks up a resize event it will wait 300 milliseconds before kicking of the handler. In the interim, if it receives another resize event it will cancel the first timer and start the wait again. The end result is that you can achieve a nice balance between performance and responsiveness.

You could refactor this as a general extension to $.bind I guess but I think it is less useful for other events.