How to reload an iframe every x seconds?

by filiberto , in category: Javascript , a year ago

How to reload an iframe every x seconds?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , a year ago

@filiberto 

To reload an iframe every x seconds, you can use the setInterval() function in JavaScript. Here's an example code snippet that demonstrates how to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
  <head>
    <script>
      window.onload = function() {
        // Reload the iframe every 5 seconds
        setInterval(reloadIframe, 5000);
      }

      function reloadIframe() {
        var iframe = document.getElementById('myIframe');
        iframe.src = iframe.src; // Reload the iframe by setting the src attribute again
      }
    </script>
  </head>
  <body>
    <iframe id="myIframe" src="https://www.example.com"></iframe>
  </body>
</html>


In the above code, the setInterval() function is called with a reference to the reloadIframe() function and a time interval in milliseconds (in this case, 5000 milliseconds or 5 seconds). This will reload the iframe with the id myIframe every 5 seconds.


Note: It's important to use the window.onload event to ensure that the script only executes after the DOM has finished loading.