Using jQuery to loop thru DOM objects with optional delay

· 9 Comments · in JavaScript, jQuery

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.

This entry was posted in JavaScript, jQuery and tagged .
Bookmark the permalink.

9 Responses to Using jQuery to loop thru DOM objects with optional delay

  1. clarke ulmer says:

    Thanks! Your comment makes the time I spent on this article worthwhile.

  2. 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 .

  3. Anonymous says:

    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

  4. TramadolInfo says:

    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!

  5. hi says:

    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!

  6. 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.

  7. Lawrence says:

    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.

  8. 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.

  9. Brooke says:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">