Michael Broschat
Michael Broschat

Reputation: 875

Loop through a set of names, taking action at interval

In an HTML page using JavaScript/jQuery, I have an array of image file names (arListx). On that page, I have a routine called show(pict) that processes the image in certain ways, then displays it.

I want to simulate a slideshow by running each image through show(pict) at a specific interval.

The best luck I've had so far is getting the final image to show (evidently, all the images are run through the code but only the last shows).

Using my interpretation of 5226285 (settimeout-in-a-for-loop-and-pass-i-as-value), I came up with this:

function doSetTimeout(i) {
  setTimeout(function() { show(arListx[i]); }, 5000);
}
.
.
.
//[main]
for(i=0; i<arListx.length; i++) {
    doSetTimeout(i);
}
.
.
.
function show(pict) {
    $("#OurPicture").attr('src',pict);
  .
  .
  .
}

I'm obviously doing something wrong and would appreciate any suggestion.

Upvotes: 2

Views: 54

Answers (1)

lucuma
lucuma

Reputation: 18339

You need to incrementally set your timeout with i*5000 so that they display at 0, 5000, 10000, 15000, etc. What you wrote just calls them all after 5 seconds.

function doSetTimeout(i) {
  setTimeout(function() { show(arListx[i]); }, i*5000);
}
.
.
.
//[main]
for(i=0; i<arListx.length; i++) {
    doSetTimeout(i);
}
.
.
.
function show(pict) {
    $("#OurPicture").attr('src',pict);
  .
  .
  .
}

Upvotes: 2

Related Questions