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
- Select multiple Dates in jQuery DatePicker
- Generate a random string in JavaScript
- Check if a String is in Uppercase or Lowercase in JavaScript
- How to highlight searched text using JavaScript
- How to search an array in JavaScript
Demo Application
Output - How to wait resize end event and then perform an action using JavaScript - Clue Mediator
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.
<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.
index.html
<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>
<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>
Run the HTML file and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐