0

I want to cycle through a bunch of jpg pictures as a slideshow. I have been using setInterval with success so far. However, I now want to have each slide show for a custom time. For example slide 1 shows for 6 seconds, then slide 2 for 3 seconds, etc. I tried the following code:

var sl = [["PodLoop1.jpg", 6000], ["PodLoop2.jpg", 3000]];
$.each(sl, function(i, value) {
    fl = '<img src="media/' + value[0] + '" height="100%">'
    setTimeout(function(){
        $("#InnerMedia").html(fl);
        if (i >= sl.length) {
            window.location.href = "./media.php"; // refresh to restart from the beginning
        }
    }, value[1])
});

But this doesn't work. It just jumps to the last slide in the list. What am I doing wrong? I have looked at several similar questions on SO, for example this one, but none of them seem to deal with a variable timer.

0

2 Answers 2

1

i will never be equal sl.length change the code to i >= sl.length-1

Sign up to request clarification or add additional context in comments.

1 Comment

Good point. I missed it. +1 :-) But this is a partial answer as user wishes to chain events.
0

Your issue is you are using .each loop.

setTimeout

What setTimeout does is it registers an event at designated time. Now when you run this in loop, this will register 2 events, 1 at after 3secs and another at after 6secs. So it runs correctly.

To fix this, you will have to chain initialisation of these setTimeouts. You will have to register new event inside another one.

Sample

function createTimeout(arr, index){
  if(!arr[index] == undefined) return;
  setTimeout(function(){
    console.log(arr[index][0]);
    createTimeout(arr, ++index)
  }, arr[index][1])
}

var sl = [["PodLoop1.jpg", 6000], ["PodLoop2.jpg", 3000]];
createTimeout(sl, 0);

6 Comments

Wouldn't recursion be a problem when I have a longer list?
if(!arr[index] == undefined) return; will make sure it does not go in endless loop
I was referring to the state where I have a 100 files (say) the memory usage will be huge! Because recursion...
@Chiwda No. You are passing reference and index to function. So it will not have that huge impact.
See this answer especially the discussion on memory towards the end.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.