Home  >  Article  >  Web Front-end  >  How to Prevent Multiple Resize Events in JavaScript/jQuery?

How to Prevent Multiple Resize Events in JavaScript/jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 11:56:02864browse

How to Prevent Multiple Resize Events in JavaScript/jQuery?

Preventing 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:

Implementation Using waitForFinalEvent

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>

Usage Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn