Open In App

How to wait resize end event and then perform an action using JavaScript ?

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When we resize the browser window, the "resize" event is fired continuously, multiple times while resizing. We want the "resize" event to only be fired once we are done resizing.

Prerequisite: To solve this problem we use two functions: 

Example: We will use setTimeout() so that the function that we want to be fired after resizing waits for 500ms. Now, we keep the setTimeout() function in the "resize" event. Right before setTimeout(), we set clearTimeout (), which keeps clearing this setTimeout() timer. Since the resize event is fired continuously when we resize the window, due to the clearTimeout() is also called continuously. Due to this, the function inside setTimeout() does not run until we stop resizing.

html
<!DOCTYPE html>
<html>
<body>
    <div id="message"></div>
    <script>
    var message = document.getElementById("message");
    var timeOutFunctionId;
    function workAfterResizeIsDone() {
        message.innerHTML += "<p>Window Resized</p>";
    }
    window.addEventListener("resize", function() {
        clearTimeout(timeOutFunctionId);
        timeOutFunctionId = setTimeout(workAfterResizeIsDone, 500);
    });
</script>

</body>
</html>

Output:

output1

Note: The code will wait 500ms after we are done resizing to fire the function we want to run after we are done resizing.


Next Article

Similar Reads