Home > Web Front-end > JS Tutorial > body text

How to Trigger an Action Only After the Resize Event Completes?

Barbara Streisand
Release: 2024-11-06 12:24:03
Original
327 people have browsed it

How to Trigger an Action Only After the Resize Event Completes?

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!