Developers often encounter the issue of handling multiple triggers of the 'resize' event during the resizing process. This can lead to unwanted behaviors or inefficiency. Understanding how to wait for the 'end' of the 'resize' event is crucial to ensure only the desired action is executed once.
One common approach, as demonstrated in the given code sample, is to use the $(window).resize(function(){resizedw();}) method. However, this method triggers the resizedw() function multiple times during the ongoing resizing process.
To overcome this, we can harness the setTimeout() and clearTimeout() methods. This strategy allows us to set a delay before triggering the resizedw() function. By setting a timeout of, for instance, 100ms, we can wait for a specific amount of time to ensure the resizing has completed. During this delay, any new resize events will 'reset' the timer, guaranteeing that it only executes once the resizing process is truly finished.
Here's a code example to illustrate this approach:
function resizedw(){ // Haven't resized in 100ms! } var doit; window.onresize = function(){ clearTimeout(doit); doit = setTimeout(resizedw, 100); };
This code sample can be found on jsfiddle for your convenience.
The above is the detailed content of How to Prevent Multiple 'resize' Event Triggers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!