I am trying to use JQuery to iterate through a number of <li> objects using a timer, i.e. - for every 5 seconds, I would like to access the next <li> object of my <ul>.
I know you can iterate using the .each function, but I am having trouble with integrating the timer with it to iterate through each one individually.
I tried the following, but it was not working correctly. It kept giving me the last LI element. I am assuming it is because setTimeout is not sequential.
$("#div_image_thumb ul li").each(function(){
var myLIobj = $(this);
setTimeout(function(){doThis(myLIobj);}, 5000);
});
John Fishers approach looks good. But if you want to stick with jQuery's each, which is quite elegant, try this (based on JasonWoof's hint to set timeouts to 5s, 10s etc.):
$("#div_image_thumb ul li").each(function (i) {
var $li = $(this);
setTimeout(function () { doThis($li); }, 5000 * (i + 1));
});
Something like this ought to work properly:
var elements = $("#div_image_thumb ul li");
var index = 0;
var doNext = null;
doNext = function() {
var element = elements.eq(index);
// do work
if (index < elements.length) {
index++;
setTimeout(doNext, 5000);
}
}
Based on your comment to the accepted answer - You want to continue looping through the collection of elements, for this you can use a setInterval and some helping functions
$(function() {
var $lis = $("#div_image_thumb ul li");
var index = 0;
// setup a function to show the current one and increase the index
var doNext = function() {
// assuming doThis is defined somewhere else.
doThis($lis.eq(index));
// increment the index - if it is beyond the number of li's - reset it to 0
if (++index >= $lis.length) index = 0;
};
// call it once as we load
doNext();
// set it up to be called every 5000 ms
setInterval(doNext, 5000);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With