2

I have several of html class's incrementing up in class name such as:

<div class="chicken1">
    <b></b>
</div>
<div class="chicken2">
    <b></b>
</div>
<div class="chicken3">
    <b></b>
</div>

I'm trying to write a for loop which will loop through these class names, adding the index to the end each class name and then calling a function in 2s delays.

for ( var i = 1; i <= 3; i++ ) {
    setTimeout(function() {
        myFunction(".chicken" + i + " b");
    }, 2000 * i);
}

However this isn't working.

Fiddle

7
  • 2
    1. where is your myFunction. 2. You are passing a string rather than a dom Commented Dec 2, 2014 at 8:19
  • 2
    What's the expected outcome? Commented Dec 2, 2014 at 8:21
  • myfunction is a function above the code.... I didn't provide it in order to simplify the question. Commented Dec 2, 2014 at 8:23
  • I'm curious to know why do you want to do that ? This has all symptoms of a bad pattern. @ramr please add this function for us to see what's wrong in your code, because currently the only thing we get when running your code is myFunction is not a function so I doesn't help. Commented Dec 2, 2014 at 8:24
  • 1
    @ramr I've updated your fiddle with a few JS tricks, have a look jsfiddle.net/pomeh/3gqfh35t/1. The code is not working at the moment but that's not my point here (hope you learn some tricks). Cheers Commented Dec 2, 2014 at 8:45

3 Answers 3

1

The problem is actually that of setTimeout() called within a loop; to do this properly you have to close over the loop variable:

for (var i = 1; i <= 6; ++i) {
    setTimeout((function(i) {
        return function() {
            myFunction(".chicken" + i + " i");
        };
    })(i), i * 2000);
}

Demo

It uses a function that gets called immediately, passing the value of i; this value is retained until the setTimeout() is fired.

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

Comments

0

are you using jquery? try

for ( var i = 1; i <= 3; i++ ) {
    myFunction($(".chicken" + i + " b"));
}

in jquery, to select elements,class etc. we need $("<selector here>");

Comments

0

This works fine for me:

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>

<div class="chicken1">
    <b></b>
</div>
<div class="chicken2">
    <b></b>
</div>
<div class="chicken3">
    <b></b>
</div>


<script>
    $( document ).ready(function() {
        for ( var i = 1; i <= 3; i++ ) {
            $(".chicken"+i+" b").html("Hey " + i);
        }
    });
</script>

</body>
</html>

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.