Luka Čelebić
Luka Čelebić

Reputation: 1093

Need to add time delay between .each elements

I need help inserting something llike a delay between executing that "code()".For example I want it to execute one after another every 4 seconds.So like first one executes, that after 4 seconds the code executes again and so on for each of the elements with given class.

Im also using .this in that "code()" so I need it to stay there because for example im getting the id of every given class and using that.

var myFunction = function(){

        $(".someClass").each( function(){

            if( this.style.opacity != "0.5" ){


                code();


            }

        });
    };

Upvotes: 0

Views: 111

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You could simply use each loop index to delay it using timeouts:

var myFunction = function() {
  $(".someClass").each(function(i) {
    setTimeout(function() {
      if (this.style.opacity != "0.5") {
        code();
      }
    }.bind(this), i * 4000); // bind relevant context
  });
};

Other version, using filter():

var myFunction = function() {
  $(".someClass").filter(function(){
    return this.style.opacity != "0.5";
  }).each(function(i) {
    setTimeout(code.bind(this), i * 4000);
  });
};

Upvotes: 3

Related Questions