Home > Web Front-end > JS Tutorial > How to Prevent Multiple $(window).resize Event Firings?

How to Prevent Multiple $(window).resize Event Firings?

Mary-Kate Olsen
Release: 2024-11-05 21:48:02
Original
576 people have browsed it

How to Prevent Multiple $(window).resize Event Firings?

Addressing Multiple Resize Event Firings with $(window).resize

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template