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.

Community
  • 1
  • 1
Chiwda
  • 1,233
  • 7
  • 30
  • 52

2 Answers2

1

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

Star089
  • 47
  • 2
  • 11
  • Good point. I missed it. +1 :-) But this is a partial answer as user wishes to chain events. – Rajesh Mar 26 '17 at 16:25
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);
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Wouldn't recursion be a problem when I have a longer list? – Chiwda Mar 27 '17 at 09:21
  • `if(!arr[index] == undefined) return;` will make sure it does not go in endless loop – Rajesh Mar 27 '17 at 09:24
  • I was referring to the state where I have a 100 files (say) the memory usage will be huge! Because recursion... – Chiwda Mar 27 '17 at 10:36
  • @Chiwda No. You are passing reference and index to function. So it will not have that huge impact. – Rajesh Mar 27 '17 at 11:29
  • See [this answer](http://stackoverflow.com/a/7023678/989468) especially the discussion on memory towards the end. – Chiwda Mar 28 '17 at 04:24
  • @Chiwda If you notice, we are passing reference of array and mentioned answer is creating `bigArray` inside function call. So in our case, closure will not be created as values are passed as arguments. So this, in my understanding, will not create memory issues. – Rajesh Mar 28 '17 at 05:42