Nick Gammon said: That's Windows for you Fiendish. If I don't pass on the WM_SIZE when I get them when am I supposed to do it?
Many browsers have the same issue with the onresize event. A common practice is to delay the event by 50-100ms, and if another onresize occurs during that period, the timer is reset. It basically waits until the last onresize has arrived.
function delay(f, time) {
var id = null;
return function() {
var context = this;
var args = Array.prototype.slice(arguments);
if (id) { window.clearTimeout(id); }
id = window.setTimeout(function() {
id = null;
f.apply(context, args);
}, time);
};
}
$(window).resize(delay(function() {
// do stuff
}, 100));
Another approach is to wait 100ms from the first onresize and ignore any others until the time is up, at which point you act on the event and start accepting onresize events again. This guarantees a more regular frequency for handling resize events, since you always respond after 100ms. The first approach ensures that only one onresize is handled.
function wait(f, time) {
var id = null;
return function() {
var context = this;
var args = Array.prototype.slice(arguments);
if (!id) {
id = setTimeout(function() {
id = null;
f.apply(context, args);
}, time);
}
};
}
$(window).resize(wait(function() {
// do stuff
}, 100));
I suppose this is similar to "debouncing" in electronics, although in that case the event is handled immediately and there's a cooldown. But that's not really what you want in the resize-event case.
[EDIT]: Code examples! I already had the first written, so I threw it in and added the second. |