'infinitetly loop array with setTimeout javascript

I have an array of strings that I'm passing to a for loop with a setTimeout inside. I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

if (x == links.length) { loopUrls() }

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)



Solution 1:[1]

If I understand correctly, you want for every link to have some function that is being executed every X milliseconds.

In order to achieve this I think it's better to use setInterval.

You can do something like:

links.forEach((link) => {
  setInterval(() => {
    //do something every X milliseconds
  }, X)
})

Solution 2:[2]

a way to do that :

// const links = [ ... ]

const myImg = document.queryselector('#ifURLS')

function LoadImg()
  {
  let 
    indx = 0
  , let refIntv = 
      setInterval( ()=>
        {
        myImg.src = links[indx++]
      
        if (indx >= links.length)
          clearInterval( refIntv ) 
        }
        , 5000 )  // 5s delay
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marian150
Solution 2 Mister Jojo