variable timer with setTimeout() inside jQuery .each

Chiwda Source

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.

javascriptjquerytimersettimeout

Answers

answered 1 year ago Rajesh #1

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);

answered 1 year ago Star089 #2

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

comments powered by Disqus