Home > Web Front-end > JS Tutorial > How to Execute $(window).resize() Only Once After Window Resizing is Complete?

How to Execute $(window).resize() Only Once After Window Resizing is Complete?

Barbara Streisand
Release: 2024-11-04 22:38:02
Original
773 people have browsed it

How to Execute $(window).resize() Only Once After Window Resizing is Complete?

Targeting Event Completion: $(window).resize() After Execution

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

To utilize this solution, follow these steps:

  1. Implement a custom event listener for window resizing.
<code class="javascript">$(window).resize(function () {</code>
Copy after login
  1. Within the event listener, invoke waitForFinalEvent to set a timeout for the callback.
<code class="javascript">    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");</code>
Copy after login

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!

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