How to wait resize end event and then perform an action using JavaScript
Today we will show you how to wait for the end of reisze event and then perform an action using JavaScript. When we resize the browser window, the “resize” event is called repeatedly during the resizing process. We want the “resize” event to trigger only after we’ve finished resizing.
Checkout more articles on JavaScript
Demo Application
Script to capture resize end event
Here, we’ll use the setTimeout()
and clearTimeout()
methods to capture the reisze end event. Look at the following script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <script> // timeOutFunctionId stores an ID which is used by clearTimeOut to reset timer var timeOutFunctionId; // The function that we want to execute after we are done resizing function workAfterResizeIsDone() { } // The following event is triggered continuously while we are resizing the window window.addEventListener("resize", function () { // clearTimeOut() resets the setTimeOut() timer due to this the function in setTimeout() is fired after we are done resizing clearTimeout(timeOutFunctionId); // setTimeout returns the numeric ID which is used by clearTimeOut to reset the timer timeOutFunctionId = setTimeout(workAfterResizeIsDone, 500); }); </script> |
Let’s take an example where we will add a text message after the resize event is completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <!DOCTYPE html> <html lang="en"> <head> <title>How to wait resize end event and then perform an action using JavaScript - Clue Mediator</title> <style> body { font-family: Arial, Helvetica, sans-serif; } </style> </head> <body> <h3>How to wait resize end event and then perform an action using JavaScript - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h3> <div id="message"></div> <script> var message = document.getElementById("message"); // timeOutFunctionId stores an ID which is used by clearTimeOut to reset timer var timeOutFunctionId; // The function that we want to execute after we are done resizing function workAfterResizeIsDone() { message.innerHTML += "<p>Window Resized</p>"; } // The following event is triggered continuously while we are resizing the window window.addEventListener("resize", function () { // clearTimeOut() resets the setTimeOut() timer due to this the function in setTimeout() is fired after we are done resizing clearTimeout(timeOutFunctionId); // setTimeout returns the numeric ID which is used by clearTimeOut to reset the timer timeOutFunctionId = setTimeout(workAfterResizeIsDone, 500); }); </script> </body> </html> |
Run the HTML file and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂