简体   繁体   中英

jQuery - traversing continuously with a delay

I have a bunch of tabs that activate different pages of content and I'd like them to loop automatically until the user clicks on one of them.

$("#projects_list ul li a").each(function() {
 activatetab($(this));
});

So I want activatetab($(this)) to be executed every say 5000ms and once the final tab is activated it should start all over again. Can it be done this way? I can probably make a function like activate_next_tab() and then call it in setInterval() while tracking which tab was last activated and then finding the next one... but it's a bother. I want to do it this way.

Thanks

Something like:

var as = $("#projects_list ul li a"), i = 0, l = as.length;
setInterval(function(){
  activatetab($(as[i++ % l]))
}, 5000)

Some explanations:

  • as is a jQuery object with the list of all A tags
  • i is the counter
  • l is the number of A tags
  • the setInterval will repeat the function every 5000ms
  • i++ will increment the counter at every pass, and % l will insure that you never go over the number of A and "rotate"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM