When utilizing $(window).resize(function() { ... }) to monitor browser window resizing, you may encounter multiple event firings during manual window adjustment. This issue arises as the event triggers each time the window border is dragged, resulting in undesirable behavior. To address this, let's explore a solution that ensures execution occurs solely after the resizing process is complete.
The code snippet below provides a practical solution that can be utilized in various parts of your code:
<code class="javascript">var waitForFinalEvent = (function () { var timers = {}; return function (callback, ms, uniqueId) { if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; } if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); } timers[uniqueId] = setTimeout(callback, ms); }; })();</code>
To utilize this solution, follow these steps:
<code class="javascript">$(window).resize(function () {</code>
<code class="javascript"> waitForFinalEvent(function(){ alert('Resize...'); //... }, 500, "some unique string");</code>
The 500 parameter represents a delay of 500 milliseconds, allowing sufficient time for the resizing process to complete. The uniqueId parameter ensures that multiple callbacks can utilize the same timeout mechanism without interference.
This modified solution allows you to define multiple callbacks that execute after window resizing is complete, catering to various sections of your code effectively.
The above is the detailed content of How to Execute $(window).resize() Only Once After Window Resizing is Complete?. For more information, please follow other related articles on the PHP Chinese website!