Home > Article > Web Front-end > How to Prevent Multiple Resize Events in JavaScript/jQuery?
When using $(window).resize, you may encounter multiple firing of the event during manual window resizing. To resolve this issue and ensure that the function is called only once after the resize is complete, consider the following solution:
This modified version of a solution from CMS allows multiple invocations in different 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>
Integrate the waitForFinalEvent function into your code as follows:
<code class="javascript">$(window).resize(function () { waitForFinalEvent(function(){ alert('Resize...'); //... }, 500, "some unique string"); });</code>
This ensures that when the window resize is complete, the callback function specified in waitForFinalEvent will be executed with a delay of 500 milliseconds. The unique ID parameter prevents conflicts when using multiple callbacks for window resizing.
The above is the detailed content of How to Prevent Multiple Resize Events in JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!