1

I would like to loop through all my .selector class elements and each time I would like it to wait x seonds before it adds class and run it's queue function

    $(".selector").each(function (i) {
        i = 1 + i;
        // like .delay(1000*i) before next event

        $(this).addClass('show').delay(2000*i).queue(function( next ){
            $(this).find('.achildselector').addClass('class');
            next();
        });

    });

so in psuedo code. Add class after xi seconds and after xi seconds add another class for each selector

2
  • It's really not clear exactly what you're trying to do, but if you want to run this logic every X seconds, wrap this code block in a setInterval() call. Commented Jan 26, 2018 at 10:33
  • right I can wrap that in a SetInterval with like 1000*i but that wont work. Commented Jan 26, 2018 at 10:35

2 Answers 2

1

If I understand correctly. you want to add a class to each of the parents with interval, and within each parent add a class to child with an interval. Something like this?

$(document).ready(function() {

  $(".selector").each(function(index, element) {
    var i = index + 1;
    setInterval(function() {
      $(element).addClass('show');
      $(element).find('.achildselector').each(function(spanIndex, span) {
        var j = spanIndex + 1;
        setInterval(function() {
          $(span).addClass('class');

        }, j * 1000);
      });
    }, i * 2000);

  });
});
.selector {
  width: 100%;
  background-color: #000;
  color: #fff;
  margin-bottom: 5px;
}

.show {
  border: 1px solid yellow;
}

span {
  color: red;
}

.class {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selector">
  Div 1
  <span class="achildselector">child 1</span>
  <span class="achildselector">child 2</span>
  <span class="achildselector">child 3</span>
</div>
<div class="selector">
  Div 2
  <span class="achildselector">child 1</span>
  <span class="achildselector">child 2</span>
  <span class="achildselector">child 3</span>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

I believe your problem is that you are loosing reference to the elements on every iteration and that is why you could use the closure to hold the values, like this:

$(".selector").each(function (i) {
    i = 1 + i;
    // like .delay(1000*i) before next event

    (function(e, delay) {
        return function() {
            e.addClass('show');
            setTimeout(function() {
                e.find('.achildselector').addClass('class');
            }, delay);
        }
    })($(this), 1000*i);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.