Home > Web Front-end > JS Tutorial > How to Execute a Function Only Once After Window Resizing in JavaScript/jQuery?

How to Execute a Function Only Once After Window Resizing in JavaScript/jQuery?

Mary-Kate Olsen
Release: 2024-11-04 15:58:01
Original
682 people have browsed it

How to Execute a Function Only Once After Window Resizing in JavaScript/jQuery?

Delayed Execution after Window Resizing in JavaScript/jQuery

The $(window).resize event in JavaScript and jQuery is triggered when the browser window resizes. However, it often fires multiple times during manual resizing by dragging the window edge.

Achieving Single-Time Invocation:

To call a function only once after the resize is complete, a timer can be used to delay execution until the resizing process has finished. Here's a solution:

Solution:

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

<code class="javascript">$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});</code>
Copy after login

In this solution, a unique identifier is used for each callback to handle multiple event registrations.

This approach ensures that the callback function is called only once, after a specified delay, giving enough time for the resizing to complete and prevent redundant event firing.

The above is the detailed content of How to Execute a Function Only Once After Window Resizing in JavaScript/jQuery?. 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