Home > Article > Web Front-end > How to Prevent Multiple $(window).resize Event Firings?
In web development, manipulating the browser window size using the $(window).resize event can trigger multiple firings. To address this, we explore a solution that executes a function only after the resize operation is complete.
Solution:
To call a function after the browser window resize is complete, we can utilize the waitForFinalEvent function. This function takes a callback function, a millisecond delay, and a unique identifier as arguments. The function sets a timeout for the callback based on the delay, but it also checks if a previous timeout with the same unique ID exists. If so, it cancels the previous timeout and sets the new one.
Implementation:
<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>
Usage:
Implement the waitForFinalEvent function in your code as follows:
<code class="javascript">$(window).resize(function () { waitForFinalEvent(function(){ alert('Resize...'); //... }, 500, "some unique string"); });</code>
By providing a unique ID for each callback, this implementation ensures that separate callbacks do not interfere with each other's timeout events. Thus, the function will only be executed after the resize operation is complete, preventing multiple firings.
The above is the detailed content of How to Prevent Multiple $(window).resize Event Firings?. For more information, please follow other related articles on the PHP Chinese website!