Paul Irish

Making the www great

Debounced Resize() jQuery Plugin

If you’ve ever attached an event handler to the window’s resize event, you have probably noticed that while Firefox fires the event slow and sensibly, IE and Webkit go totally spastic.

PPK lays it out like this:

  • In IE, Safari, and Chrome many resize events fire as long as the user continues resizing the window.
  • Opera uses as many resize events, but fires them all at the end of the resizing.
  • Firefox fires one resize event at the end of the resizing.

When I first saw John Hann’s debounce post, this use case is what I immediately thought of.

This isn’t exactly throttling, but it’s close. Basically debouncing will fire your function after a threshold of time (e.g. 100ms) has elapsed since the last time it’s tried to fire. Throttling would withhold subsequent firings, but debouncing waits for the last one and runs that.

Take a look at the difference on the demo.

The code for smartresize:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize 
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


// usage:
$(window).smartresize(function(){
  // code that takes it easy...
});

Pretty straightforward stuff. What else do you think would be an appropriate use of debounce()?

Comments