Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery to Iterate through elements with a timer

Tags:

jquery

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);
});
like image 823
Bamerza Avatar asked Sep 08 '09 20:09

Bamerza


3 Answers

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));
});
like image 69
Fabian Avatar answered Nov 02 '22 07:11

Fabian


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);
  }
}
like image 26
John Fisher Avatar answered Nov 02 '22 07:11

John Fisher


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);
});
like image 3
gnarf Avatar answered Nov 02 '22 07:11

gnarf