Using JQuery to Call RESIZE Event When Resizing Completes
When developing responsive applications, it's often necessary to track browser window size changes to adjust the UI accordingly. However, continuously calling a resize function while the window is being manually resized can lead to excessive function calls.
To address this issue, JQuery provides a way to call the resize function only once after the window has finished resizing.
Solution Using setTimeout()
In JQuery's resize event listener, use a setTimeout() function to call the desired action with a specified delay. This ensures that the function is only called after the resizing has stopped.
$(window).resize(function() { if (this.resizeTO) clearTimeout(this.resizeTO); this.resizeTO = setTimeout(function() { $(this).trigger('resizeEnd'); }, 300); }); $(window).on('resizeEnd', function() { // Code to be executed after resizing is complete });
In this solution, a resizeEnd custom event is triggered after a 300ms delay, guaranteeing that it occurs only after the resizing has finished.
Other Solution Using setInterval()
Alternatively, you can use setInterval() to continuously check if the window size has changed. When the size remains stable for a specified duration, the resize function is called.
var resizeInterval; window.onresize = function() { if (resizeInterval) clearInterval(resizeInterval); resizeInterval = setInterval(function() { if (window.innerWidth == previousWidth && window.innerHeight == previousHeight) { clearInterval(resizeInterval); // Code to be executed after resizing is complete } }, 300); previousWidth = window.innerWidth; previousHeight = window.innerHeight; };
In both solutions, the delay value can be adjusted according to the application's requirements.
The above is the detailed content of How to Call JQuery's RESIZE Event Only When Resizing Completes?. For more information, please follow other related articles on the PHP Chinese website!