"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to perform an operation after the window resize is completed?

How to perform an operation after the window resize is completed?

Posted on 2025-04-14
Browse:718

How to Execute Actions Only After a Resize Operation Has Finished?

Waiting for the 'End' of 'resize' Event for Optimal Action Execution

In event-driven programming, it's common to handle size changes using the 'resize' event, typically assigned to a window or other resizable element. However, when resizing operations occur, the 'resize' event is triggered multiple times during the process, leading to redundant execution of your event handler.

Capturing the 'End' of a 'resize' Event

To address this issue and execute an action only when the resizing has concluded, we can employ a technique that involves the use of 'setTimeout()' and 'clearTimeout()'.

Solution:

Create a function, 'resizedw()', which will serve as your event handler for the resizing action.

function resizedw() {
  // Your action to be performed when resizing finishes
}

Declare a variable, 'doit', and initialize it as 'null'. This variable will hold the timeout id returned by 'setTimeout()'.

var doit = null;

Attach the event listener to the 'onresize' event of the 'window' object.

window.onresize = function() {

Use 'clearTimeout()' to cancel any pending timeout request associated with the 'doit' variable.

  clearTimeout(doit);

Assign the result of 'setTimeout()' to the 'doit' variable. This will schedule the execution of 'resizedw()' after a delay of 100 milliseconds.

  doit = setTimeout(resizedw, 100);
};

When the resizing operation ends, the 'onresize' event handler will be invoked without triggering 'resizedw()' immediately. After the designated delay (100 milliseconds), 'resizedw()' will execute, marking the completion of the resizing process.

Example Code:

The following code demonstrates the implementation of this approach:

function resizedw() {
  // Your action to be performed when resizing finishes
  console.log('Resizing finished!');
}

var doit = null;
window.onresize = function() {
  clearTimeout(doit);
  doit = setTimeout(resizedw, 100);
};

This solution effectively handles the 'resize' event by preventing the associated action from executing during the resizing process. Instead, the action is triggered only after the resizing operation has fully concluded.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3