Home >Web Front-end >JS Tutorial >How to Trigger a jQuery Resize Event Only Once After Resizing is Complete?
How to Call the jQuery Resize Event Only Once after Resizing is Complete
Problem Overview
When using jQuery's resize event to invoke a function, it may get called repeatedly as the user resizes the browser window. The goal is to trigger the function only once when resizing has been completed.
Solution
To achieve this, we can utilize the setTimeout function and a timeout variable:
var timeout; $(window).resize(function() { // Function to execute when resizing is complete timeout = setTimeout(function() { // Execute the desired function }, 30); });
By setting a timeout of 30 milliseconds, we delay the execution of the function until the resizing has stopped for at least 30 milliseconds. This ensures that the function is only called once.
Additional Considerations
If the user initiates another resizing action before the timeout expires, the previous timeout will be cleared and a new one will be set. This ensures that the function is always executed only once after the final resize.
Caution: Using global variables, such as timeout, should be avoided if possible. However, in this case, the use of a timeout variable is necessary to maintain the state of the event handling.
The above is the detailed content of How to Trigger a jQuery Resize Event Only Once After Resizing is Complete?. For more information, please follow other related articles on the PHP Chinese website!