Search code examples
htmlloopsiframesettimeoutsetinterval

how do i change iframe src in setinterval loop


I need to change the link of an iframe in loop, without a button, i try to do with a click but it doesnt work, how can i do this loop and src change?

i try this:

<iframe src="https://Google.com" name="iframe_a" height="100%" width="100%" title="Iframe Example" /iframe



<button onclick="setInterval(link, 3000);">Try it /button>;

<button onclick="setInterval(link2, 10000);">Try it2 /button>

<script>

    function link() {
      
    <a href="https://stackoverflow.com" target="iframe_a">
    }

    function link2() {

    <a href="https://google.com" target="iframe_a">
     }

</script>

EDIT--------------

I managed to change the links but I couldn't create the loop

`<iframe id='the_iframe'></iframe> 
<script> var urls = [ 'google.com, 'stackoverflow.com ]; 
var seconds = 5; 
function openNext(){ document.getElementById('the_iframe').src = urls.shift(); 
if(urls.length)setTimeout('openNext()',seconds*1000); } 
setInterval(openNext(),5000);` // I tried to do this loop every 5000ms but didnt work </script> –

Solution

  • do something like this

    let urls = [ 'google.com', 'stackoverflow.com']; // array of all urls
    
    setInterval(()=>{
        let url = urls.shift(); // get next link
        urls.push(url); // push it to the back of the array
        document.getElementById('the_iframe').src = url; // set url
        console.log(url); // log (for debug purposes)
    },50000)
    <iframe src="https://Google.com" id="the_iframe" name="iframe_a" height="100%" width="100%" title="Iframe Example"></iframe>