Home >Web Front-end >JS Tutorial >How can I make jQuery's `resize` event function execute only once after resizing?

How can I make jQuery's `resize` event function execute only once after resizing?

DDD
DDDOriginal
2024-12-09 18:43:15289browse

How can I make jQuery's `resize` event function execute only once after resizing?

Calling jQuery RESIZE Event Only Once After Resizing

When working with the jQuery resize event function, you may encounter situations where you want the function to execute only once when the browser finishes resizing. However, the default behavior is to call the function continuously during the resizing process.

To overcome this, you can utilize a technique called "debouncing." Here's how it works:

  1. Set an Interval:
    Start a timed function using setInterval() to check if the browser is still resizing. Set a reasonable interval, such as 50-100 milliseconds.
  2. Clear Interval:
    If the browser is no longer resizing (e.g., the user has stopped dragging the window edge), clear the interval created in step 1 using clearInterval(). This ensures that the function will only be called once.
  3. Implement Debouncing:
    Within the setInterval() function, perform a check to determine if the browser is still resizing. Use the following code as an example:
$(window).resize(() => {
  let timer;
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    // Your code to execute after resizing is complete
  }, 50);  // Adjust the delay as per your requirement
});
  1. Initialize Debounce Function:
    Trigger the debouncing function by calling it immediately after setting the resize event listener. This ensures that the function is executed once when the page loads.

By implementing this technique, you can call the resize event function a single time after the browser finishes resizing, effectively resolving the issue of continuous function calls during the resizing process.

The above is the detailed content of How can I make jQuery's `resize` event function execute only once after resizing?. 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