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
Mary-Kate OlsenOriginal
2024-11-04 15:58:01678browse

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>

Usage:

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

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!

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