views:

28

answers:

3

I have what I though was a simple problem to solve (never is!) I'm trying to loop through a list of URL's in a javascript array I have made, load the first one, wait X seconds, then load the second, and continue until I start again. I got the array and looping working, trouble is, however I try and implement a "wait" using setInterval or similar, I have a structural issue, as the loop continues in the background.

I know about setTimeOut and setInterval, but haven't been able to format the code in a way that works. I'm new to javascript and as such often make various stupid mistakes, and would really appreciate being able to understand how best to structure this, as well as some working examples!

I tried to code it like this:

$(document).ready(function(){ 

// my array of URL's
var urlArray = new Array();
urlArray[0] = "urlOne";
urlArray[1] = "urlTwo";
urlArray[2] = "urlThree";

// my looping logic that continues to execute (problem starts here)

while (true) {

   for (var i = 0; i < urlArray.length; i++) {

     $('#load').load(urlArray[i], function(){

     // now ideally I want it to wait here for X seconds after loading that URL and then start the loop again, but javascript doesn't seem to work this way, and I'm not sure how to structure it to get the same effect

       });

   }

}

});
+2  A: 

You should use setTimeout() or setInterval() instead of a while loop, and manually break out when your counter limit is reached.

var count = 0;

   // Function called by setInterval
function loadIt() {
    $('#load').load(urlArray[count], function(){
           // Do your thing
      }); 

      count++;  // Increment count

      if(count == urlArray.length) {  
          count = 0;
      }
}

loadIt();    // Call the function right away to get it going

var interval = setInterval(loadIt, 5000);  // then call it every five seconds

EDIT:

Edited to bring counter maintenance out of the load() callback.

EDIT:

A prettier way of setting the count each time would be like this:

count = (count == urlArray.length) ? 0 : count + 1;
patrick dw
What do you mean manually break out, and how would I structure that? I did try to work with setTimeout() and setInterval() but the problem was it ran the loop all the way through.I do want the loop to repeat indefinitely...
Tristan
@Tristan - I've updated my answer. `setInterval()` and `setTimeout()` return a reference that you can use to clear them.
patrick dw
So with your example do I drop my for loop completely?
Tristan
@Tristan - Sorry, I didn't notice that you wanted to run infinitely. I'll update my answer to reset `count` to `0`.
patrick dw
@Patrick - I really appreciate your example, i've been stuck with this for hours. Thank you. Marking this as complete...
Tristan
@Tristan - You're welcome. :o) Sorry I didn't pay closer attention to your question (and comment) to begin with. Haste makes waste!
patrick dw
@Tristan - Keep in mind that in the answer you selected, each new `load()` request relies on the successful completion of the previous. If one gets stuck for a short (or long) while, the rest are held up. It would be better to cancel the previous request if it is delayed before you start a new one.
patrick dw
@Tristan ...also, I'll update my answer to make the first `load()` run immediately. You simply need to move the function out of the `setInterval()` and call it right away.
patrick dw
A: 

Try something like this.

var totalUrls = urlArray.length;
var currentPosition = 0;

function keepLoadingForever() {
  if (currentPosition >= totalUrls) currentPosition = 0;

   $('#load').load(urlArray[currentPosition], function(){
       setTimeout(keepLoadingForever, 5000);            //delay 5 seconds
       });
   }

  currentPosition++;
}
womp
+1  A: 

I would use a recursive solution that passes the source array and the current index of the element to load, checking to make sure that the index is within the array bounds and that I'm not scheduling unnecessary work.

function loadUrls( source, index )
{
     if (index < source.length) { // make sure this one is available
         $('#load').load( source[index], function() {
             var newIndex = index + 1;
             if (newIndex < source.length) { // don't schedule if this is last
                 setTimeout( function() { loadUrls( source, newIndex ); }, 5000 );
             }
         });
     }
} 

$(document).ready(function(){  

    // my array of URL's 
    var urlArray = new Array(); 
    urlArray[0] = "urlOne"; 
    urlArray[1] = "urlTwo"; 
    urlArray[2] = "urlThree";

    loadUrls( urlArray, 0 );
}

If you want it to infinitely recurse over the same urls, change loadUrls to:

function loadUrls( source, index )
{
     if (index < source.length) { // make sure this one is available
         $('#load').load( source[index], function() {
             var newIndex = (index + 1) % source.length;
             setTimeout( function() { loadUrls( source, newIndex ); }, 5000 );
         });
     }
}
tvanfosson
I like the way this is structured, presumably this would also have the added avantage of loading the first URL straight away, which is neat.
Tristan
@Tristan - you're right, there would be no delay in loading the first url.
tvanfosson