There is no such thing as a resize end event that you can listen to. The only way to know when the user is done resizing is to wait until some short amount of time passes with no more resize events coming. That's why the solution nearly always involves using a setTimeout()
because that's the best way to know when some period of time has passed with no more resize events.
This previous answer of mine listens for the .scroll()
event, but it's the exact same concept as .resize()
: More efficient way to handle $(window).scroll functions in jquery? and you could use the same concept for resize like this:
var resizeTimer;
$(window).resize(function () {
if (resizeTimer) {
clearTimeout(resizeTimer); // clear any previous pending timer
}
// set new timer
resizeTimer = setTimeout(function() {
resizeTimer = null;
// put your resize logic here and it will only be called when
// there's been a pause in resize events
}, 500);
}
You can experiment with the 500
value for the timer to see how you like it. The smaller the number, the more quickly it calls your resize handler, but then it may get called multiple times. The larger the number, the longer pause it has before firing, but it's less likely to fire multiple times during the same user action.
If you want to do something before a resize, then you will have to call a function on the first resize event that you get and then not call that function again during the current resize operation.
var resizeTimer;
$(window).resize(function () {
if (resizeTimer) {
clearTimeout(resizeTimer); // clear any previous pending timer
} else {
// must be first resize event in a series
}
// set new timer
resizeTimer = setTimeout(function() {
resizeTimer = null;
// put your resize logic here and it will only be called when
// there's been a pause in resize events
}, 500);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…