bindWithDelay jQuery Plugin

Sometimes, I want to have a JavaScript event that doesn't fire until the native event stops firing for a short timeout. I've needed to use that pattern in almost every project I have worked on.

For example, you want to use JavaScript to resize an iframe to 100% height when the window resizes. The resize() event can fire dozens of times, and calculating and setting the new height can slow down your page. I used to implement it like this (notice the extra global variable and indentation with the anonymous function):

var timeout;
function doResize(e) {
   clearTimeout(timeout);
   timeout = setTimeout(function() {
      // run some code
   }, 200);
}
$(function() {
   $(window).bind("resize",doResize);
});

I wrote a plugin to make this pattern easier, it is called "bindWithDelay". The source code is online, as is a mini project page with a demo.

This is what the same code looks like with the plugin:

function doResize(e) {
  // run some code
}
$(function() {
   $(window).bindWithDelay("resize", doResize, 200);
});