Waiting for the End of the 'Resize' Event to Trigger an Action
Often when working with responsive design, it's desirable to perform an action only after the resizing process has completely finished. However, traditional event handling using $(window).resize() can trigger multiple calls during the resizing process, leading to undesired behavior.
Solution: Using setTimeout() and clearTimeout()
To achieve the desired behavior, a combination of setTimeout() and clearTimeout() can be employed. Here's an example:
function resizedw() { // Haven't resized in 100ms! } var doit; window.onresize = function () { clearTimeout(doit); doit = setTimeout(resizedw, 100); };
This approach utilizes a timer to delay the execution of the resizedw() function. When the resize event occurs, it clears any existing timer and starts a new one. If the resizing process continues within 100 milliseconds, the timer is reset again. Only when the resizing has stopped for 100 milliseconds does the resizedw() function get invoked.
Example on jsfiddle:
For a working example of this solution, please refer to the jsfiddle link provided in the answer.
The above is the detailed content of How to Trigger an Action Only After the Resize Event Completes?. For more information, please follow other related articles on the PHP Chinese website!