You want to loop through a collection of DOM objects, so you use .each().
But what if you want to have a delay between effects on the current item?
In short – don’t use .each() for looping – and don’t use setTimeout for the delay.
We’re going to call items by index instead, optionally using a clever way to add a delay.
You’ve probably run into this before, you loop over items using .each() and apply, say, a fade effect.
Works fine. Each item has the effect applied immediately.
But what if we wanted a delay between each item having the effect applied? There’s articles out there explaining how to use setTimeout to accomplish this but I didn’t want to go that route.
Instead we are going to have two functions.
One function calls an item in a collection by using it’s index.
The other function is our delay.
Markup
We’re going to start off with a simple collection of list items.
<ul class="ul-example"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> </ul>
jQuery
Access item via index function
Our first function we’ll name getData().
This function will access each item via it’s index, apply a fade to that item, then call our delay function.
The delay function, when completed, in turn calls our getData() function again passing it a new index increased by 1.
Keep in mind the getData() function is not “looping” through our items, it is accessing them individually based on their index. (Yeah, I know the post title says “looping” – but that’s for SEO )
function getData(i){ //set index to zero at init if( typeof(i) === "undefined" ){ var i = 0; } //our dom collection var _coll = $(".ul-example li"); //dom collection is empty or does not exist if( $(_coll).length === 0 ){ return false; } //reached end of dom collection if( i >= $(_coll).length ){ return false; } //do something to current item like fadeTo $(_coll).eq(i).fadeTo(300,0.2,function(){ //increase index by 1 i++; //only use either of these - not both //delay delayFunc( 2000, "getData(" + i + ")" ); //no delay getData(i); }); };
Delay function
For our delay, instead of using setTimeout or .delay()(which is only for animations), we are going to use .animate().
We create a jQuery object and run .animate() on it for a set period of time in milliseconds, that gives us our delay. The object doesn’t have to be appended to the DOM for .animate() to work on it. Cool, huh?
When the time interval has completed it calls the passed function, in this case our getData() function to get items via their index.
The delay function takes two arguments:
delayFunc(milliseconds, function);
The function argument must be passed as a string, example:
delayFunc( 2000, "getData(" + i + ")" );
function delayFunc(t,func){ //if no delay duration, set to zero if( typeof(t) === "undefined" ){ var t = 0; } //if no function passed, cancel if( typeof(func) === "undefined" ){ return false; } //create virtual object var _delayObj = $("<div></div>"); $(_delayObj).animate({ opacity:1 },t,function(){ //call our passed function $.globalEval(func); } ); }
* This delay function can be repurposed to add a delay whenever you need it – just remember you need to pass a function to the delay.
See the full working examples here.
Tested in:
jQuery 1.7.2+
FF 3.6+, Safari, Chrome, IE8+, iOS
Great books are available on JavaScript and jQuery
.
Thanks! Your comment makes the time I spent on this article worthwhile.
I want to say that this post is amazing, nice written and come with approximately all vital infos. I would like to peer more posts like this .
I relish, result in I found just what I used to be taking a look for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye
Pretty nice post. I simply stumbled upon your weblog and wished to mention that I’ve truly loved browsing your blog posts. After all I will be subscribing in your feed and I am hoping you write again very soon!
Great website. Plenty of useful info here. I’m sending it to several pals ans additionally sharing in delicious. And obviously, thanks for your sweat!
Los fotógrafos del instante no son pocos, con varias publicaciones en revistas
de tendencia como Vogue y Elle, los genios de la fotografía se
han ganado un puesto en el planeta de la moda.
Nada como percibir a otros más experimentados para aprender y prosperar día a día, tanto en fotografía como en muchos otros campos de la vida.
Todos hemos visto geniales trabajos fotográficos de fotógrafos
apasionados, de algún amigo colega, que
los ves y te quedas impresionadísimo; y otros de fotógrafos profesionales que no alcanzan una calidad decente mínima.
Todo esto con el único objetivo de ofrecer a nuestros
clientes la máxima calidad de fotografia y vídeo de bodas presente el mercado,
a fin de que el recuerdo tan importante de vuestras vidas, ese que vamos
a inmortalizar, no quede obsoleto con el pasar de los años.
Fabulous, what a weblog it is! This webpage provides useful data to us, keep it up.
From your viewpoint, equity crowdfunding is in fact likely a lesser amount of dangerous
for the reason that it’s a audience of consumers
buying a company rather than just a number of
brokers.
However, the couple of payment gateways available implies merchants have restricted alternatives on providers to perform with.
Formerly known as NBepay,MOL pay is 1 of the earliest Malaysian onn the web payment
gateways. Pay88 is one of the major Malaysian payment gateways that
allow tihy businesses annd corporations to accept credit cards on line.
Belpow are the significant payment gateways that enable Malaysian merchants to accspt credit cards on the net.
In the past, busnesses looking to process recurring and other forms of online
payments identified it complidated ddue to restrictions put by most international gateways on merchants from Asia.
Let us know! We are an angel investor group hunting for wonderful malaysia startups 2019 to fund.
Get in touch with us or let us know in thhe
comments! Feel free of charge to leave a comment below and let us know.
Please use the comment box below to share your thoughts and views.
In this short article, we appear at local and international
getaways that Malaysian start-ups can use to procedure oon the internet payments.
Additionally, focusing on expertise sharing, mentoring sessions
and localised expertise, the programme enabled commence-ups to lrarn initial-hand about the local begin-up eco-program,
business landscape, organization culture aand regulations.
Visit Bumiputera Entrepreneur Start-up Scheme (Superb)
ffor much more information.
Every weekend i used to go to see this web page, because i wish for enjoyment, since this this web site conations genuinely pleasant funny material too.