Lawrence
Lawrence

Reputation: 845

How to add class to a collection of elements sequentially?

Im trying to add a class to a each element in a collection. I want add a classs to the elemnt then wait a sec or two then add the class to the next one in the collection.

But when I use this code it just adds the class to each one at once.

for (var i = 0; i < article.length; i++) {
    setTimeout(function () {
        $(article[i]).addClass('something';
        }, 10000);
    }

Upvotes: 0

Views: 1202

Answers (4)

millimoose
millimoose

Reputation: 39950

An approach without having to chain calls:

for (var i = 0; i < article.length; i++) {
    (function(_i) {
    setTimeout(function () {
        $(article[_i]).addClass('something');
    }, 10000+_i*1000);
    })(i);
}

It's pretty unlikely the overhead from adding a CSS class will be significant enough to make this not behave as desired.

Upvotes: 0

Gonzy
Gonzy

Reputation: 143

You can use

var x = setInterval("javascript",ms);

and it wall call whatever is in the code section over and over again every "ms" until you call the

clearInterval(x);

function

Upvotes: 0

Engineer
Engineer

Reputation: 48793

Try something like this:

 (function step(i){         
     if( i < article.length ){
          $(article[i]).addClass('some_class');
          setTimeout(function(){ step(i+1) },10000);
     }         
 })(0);

Upvotes: 5

cdhowie
cdhowie

Reputation: 169018

The problem is that you are setting a bunch of timeouts 10 seconds from the same moment in time, so they will all execute 10 seconds later at once. You need to chain them together so that each timeout handler invokes the next timeout:

var i = 0;
var callback;

callback = function () {
    if (i < article.length) {
        $(article[i]).addClass('something');

        ++i;
        setTimeout(callback, 10000);
    }
};

setTimeout(callback, 10000);

Upvotes: 3

Related Questions