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


Whenever we resize the web page window, it triggers the ‘resize’ event by default. The ‘resize’ event triggers multiple times while resizing the window. Sometimes, we require to execute some JavaScript code only once when resize event completes.

In such cases, we must use the setTimeOut() method with the resize event to execute JavaScript code or function once the event completes. Also, we require to use the clearTimeOut() method.

Syntax

Users can follow the syntax below to wait resize event completes and then perform an action using JavaScript.

window.addEventListener('resize', () => {
   
   // It clears the previous timeout
   clearTimeout(timeId);
   
   // It creates a new timeout to execute the function
   timeId = setTimeout(function, delay);
});

In the above syntax, we have used the clearTimeOut() and setTimeOut() methods. Whenever resize event occurs, we clear the previous time out using the timeId. After that, we set to time out again for the function and store its id in the timeId variable.

Example 1 (Using the resize event with the addEventListner method)

In the example below, we have used the addEventListner() method to add resize event on the window. It will execute the callback function whenever resizing event triggers on the window. In the callback function, first, we clear the time out and set time out again for the executeAfterResize() function. If users don’t resize the window in the last 1000 milliseconds, it will execute the executeAfterResize() function.

<html>
<body>
   <h2>Executing JavaScript function when resize event completes</h2>
   <h3>Starts resizing the window</h3>
   <div id = "content"></div>
   <script>
      let content = document.getElementById('content');
      
      // function to execute JavaScript code after the window resize event completes
      function executeAfterResize() {
         content.innerHTML += "This function is executed after resize event is completed! <br>";
      }
      var timeId = null;
      window.addEventListener('resize', () => {
         clearTimeout(timeId);
         timeId = setTimeout(executeAfterResize, 1000);
      });
   </script>
</body>
</html>

Example 2 (Using the onresize event attribute)

In the example below, we have used the ‘onresize’ event attribute to execute the startResize() function whenever a user resizes the window. In the startResize() function, we have used the clearTimeOut(), and setTimeOut() methods as the first example to execute JavaScript code when resizing event is completed.

<html>
<body onresize="startResize()">
   <h3>Executing JavaScript function when resize event completes using the onresize event attribute</h3>
   <p>Starts resizing the window<p>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      function executeAfterResize() {
         content.innerHTML += "This function is executed after resize event is completed! <br>";
      }
      var timeId = null;
      function startResize() {
         clearTimeout(timeId);
         timeId = setTimeout(executeAfterResize, 1000);
      }
   </script>
</body>
</html>

Using the resize event in jQuery

Follow the below steps trigger the executeOnResizeEnd() function if users haven’t resized the window in the last 500 milliseconds.

Step 1 – Define the resetTime variable to store the current date while resizing the window, the timeout variable to store a Boolean value representing that timeout is completed, delay variable representing to execute of a function after a delay number of milliseconds when resize completes.

Step 2 – Call the callback function when resize event occurs using the jQuery.

Step 3 – Store the current time in the resetTime variable in the callback function. Also, check if the value of the ‘timeout’ variable is false, make it true, and set a timeout for the executeOnResizeEnd() function.

Step 4 – In the executeOnResizeEnd() function, check if the current time is different, the reset time is less than the delay and set a timeout for the function again. Otherwise, execute the code of the function.

Example

In the example below, we have used JQuery to execute the JavaScript code when resizing event completes. In the example below, we have used only the setTimeOut() method without using the clearTimeOut() method and followed the above steps to execute the executreOnResizeEnd() function after the completion of the resize event.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
   <h3>Executing JavaScript function when resize event completes using jQuery</h3>
   <p>Started resizing the window</p>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      var resetTime;
      var timeout = false;
      var delay = 500;
      $(window).resize(function () {
         
         // get the current time
         resetTime = new Date();
         
         // if the timeout is false, set it to true
         
         // set delay for executreOnResizeEnd function
         if (timeout === false) {
            timeout = true;
            setTimeout(executeOnResizeEnd, delay);
         }
      });
      function executeOnResizeEnd() {
         
         // if the difference between the current time and reset time is less than the delay, set timeout for function again
         if (new Date() - resetTime < delay) {
            setTimeout(executeOnResizeEnd, delay);
         } else {
            
            // if window is not resized in last 500ms, execute the below code
            timeout = false;
            content.innerHTML = "Resize event is completed. <br>"
         }
      }
   </script>
</body>
</html>

In this tutorial, users learned to wait until resizing event complements and triggers the JavaScript function. In the first two examples, we have used the clearTimeOut() and setTimeOut() methods to achieve the goal. In the third example, we have created the custom algorithm using JQuery to execute the script on resize event ends.

Updated on: 28-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements