views:

216

answers:

3

I assigned a timeout to my window.resize handler so that I wouldn't call my sizable amount resize code every time the resize event fires. My code looks like this:

<script>
function init() {
  var hasTimedOut = false;
  var resizeHandler = function() {
    // do stuff
    return false;
  };

  window.onresize = function() {
    if (hasTimedOut !== false) {
      clearTimeout(hasTimedOut);
    }
    hasTimedOut = setTimeout(resizeHandler, 100); // 100 milliseconds
  };
}
</script>
<body onload="init();">
...
etc...

In IE7 (and possibly other versions) it appears that when you do this the resize event will constantly fire. More accurately, it will fire after every timeout duration -- 100 milliseconds in this case.

Any ideas why or how to stop this behavior? I'd really rather not call my resize code for every resize event that fires in a single resizing, but this is worse.

+1  A: 

In your //do stuff code, do you manipulate any of the top,left,width,height,border,margin or padding properties?

You may unintentionally be triggering recursion which unintentionally triggers recursion which unintentionally triggers recursion...

scunliffe
Nope. All I'm doing is adding some divs.
ntownsend
...and none of those divs cause the content of the page to changed the width/height to a degree that causes the vertical or horizontal scrollbars to appear/disappear? ;-) This too can cause IE to re-fire resize events.
scunliffe
I think you're partially right. They don't make the scrollbars appear or disappear but it seems like drawing the divs is doing something to the window to make it fire resize events.When I replace my div drawing with some dummy function that doesn't really do anything I no longer see resize events constantly firing.
ntownsend
A: 

How to fix the resize event in IE

also, see the answer for "scunliffe" "In your ... properties?

andres descalzo
Thanks, but one of my constraints is that I cannot use JQuery (or any other framework) :( Maybe I can figure out what JQuery is actually doing and implement it for myself.
ntownsend
accurate, I found the link useful for you to at least get the code and use it
andres descalzo
A: 

IE does indeed constantly fire its resize event while resizing is taking place (which you must know, as you are already implementing a timeout for a fix).

I am able to replicate the results you are seeing, using your code, on my test page.

However, the problem goes away if I increase the timeout to 1000 instead of 100. You may want to try with different wait values to see what works for you.

Here is the test page I used: it has a nicely dynamic wait period already set up for you to play with.

Chris Nielsen
I didn't see this behavior with your test page.
ntownsend