0

I have a list of element ids that are randomly generated. The elements already exist, I am not creating or removing them. I just need to select random ones via their id:

stripped out HTML:

<div id="circle1"></div>
<div id="circle2"></div>
<button id="start">Start<button>

some simple JS/jQuery:

var circles = [];

function getRandomCircle() {
    return "circle" + Math.floor((Math.random() * 3) + 1);
}

function flashCircles() {
  for (var i = 0; i < circles.length; i++) {
    setTimeout(function() {
      $("#" + circles[i]).fadeTo("slow", 1, function() {
        $("#" + circles[i]).fadeTo("slow", 0.5, function() {});
      });
    }, i * 1000);
  }
}

$("#start").on("click", function() {
  circles.push(getRandomCircle());
  circles.push(getRandomCircle());
  circles.push(getRandomCircle());
  flashCircles();
});

The #circle elements are not getting selected, and thus not fading in and out. I reach the setTimeout() call, I don't get inside the callback for the initial selector. The circles.push(getRandomCircle()) calls work as expected. Nothing changes if I remove them and initialise the circles array instead. I don't think it's the array notation because if I run the following after setTimeout() and within the loop, the elements are selected as expected:

if ($("#" + circles[i]).length) {
  console.log("selected")
} else {
  console.log("not selected")
}

The only thing that works is a hard coding the id to call:

 $("#"+"circle1").doStuff();

I had this working, originally. getRandomCircle() contained a for-loop that populated the array. Nothing else has changed.

What's happening here? Array notation worked before, it works here when checking if something is selected, but it not working within setTimeout(), despite the fact it was working before. All code is wrapped in a $("document").ready() call.

  • Have you tried passing `circles` to your `flashCircles` as a parameter? Or even using `i` in your for loop as a parameter in your `setTimeout` function? I think it even makes sense not to declare `circles` outside your click event handler for encapsulation purposes – AGE Mar 16 '16 at 15:48
  • 1
    Try logging your 'i' value. You might have an async issue. – phenxd Mar 16 '16 at 15:51
  • 1
    Also why is there no i++ in the forloop? – phenxd Mar 16 '16 at 15:52
  • the counter has been logged. There is an i++, and no syntax error on my part, just rushed when asking my question. edited the original post. – monkeySeeMonkeyDo Mar 16 '16 at 15:56

0 Answers0