Home > Web Front-end > JS Tutorial > How to Prevent Multiple 'resize' Event Triggers in JavaScript?

How to Prevent Multiple 'resize' Event Triggers in JavaScript?

Linda Hamilton
Release: 2024-11-11 04:48:02
Original
535 people have browsed it

How to Prevent Multiple 'resize' Event Triggers in JavaScript?

Managing Multiple 'resize' Event Triggerings

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);
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template