views:

52

answers:

3

On jQuery resize event page it is said that:

"Code in a resize handler should never rely on the number of times the handler is called. Depending on implementation, resize events can be sent continuously as the resizing is in progress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safari and Chrome), or only once at the end of the resize operation (the typical behavior in Firefox)."

Right now I observe increasing memory leak in my app, as I'm continuously resizing browser window, which in it's turn continuously triggers specific code. I thought resize event is called only once in the end of the resize operation, but now after reading this I think my code is simply overkilling itself.

Is there any established practice to trigger a callback cross-browser only once, when resize operation has already ended?

+2  A: 

As you are using jQuery anyway, have a look at Ben Alman's doTimeout plugin. You can use it to debounce your event handler.

There is even an example that matches exactly your case:

$(window).resize(function(){
  $.doTimeout( 'resize', 250, function(){
    // do something computationally expensive
  });
});

The key here is that, the function passed to doTimeout is only executed if the resize handler is not called (i.e. the resize event is not fired) again during the next 250 ms. If so, the timer is aborted and a new one is started.

Felix Kling
Thanks :) Although your first link seems to be broken.
jayarjo
@jayarjo: Oops sorry :) Fixed.
Felix Kling
+1  A: 

I think it would help if you showed us your resize event handler.

Without seeing your code all I can suggest is to have some kind of thottle to limit how many times the handler can be triggered per second:

var lastTime = 0;
$(window).resize(function(){
    // This condition will only be met (at most) once every second
    if (lastTime + 1000 < +new Date) {
        // do your stuff...
        lastTime = +new Date;
    }
});
J-P
Not sure how a callback code maybe relevant here. But thanks for a solution :)
jayarjo
A: 

You could use a flag. Set the flag at the start of the function - unset if after the resize in complete. Then do not allow the function to be called again unless the flag has been reset.

matpol