1

I have seen this sort of information floating around but I cannot figure out why my particular setup is flashing through the function so fast.

Here is what I am trying to do:

I have squares on a page that I need to glow in order, but 500 milliseconds apart. I store the jQuery identifier in an array and cycle through it.

function glow(source) {// glows
  $(source).addClass("square-active")
  setTimeout(function() { 
    $(source).removeClass("square-active");
  }, 500);
}

function iterator() {
  var y = 0;
    setTimeout(function() {
     for (var t=0; t<newComp.slice(0, numTurn).length; t++) {
          glow(squareArr[newComp[t]].div) 
       y = y + 1
} 
    }, 500 * y)
      }

I know that the squares are being iterated through properly because I have that logged to the console for verification purposes. I can see the squares flash in order, but it is insanely fast.

When I attempt to wrap the glow() function in setInterval I do not believe it works either.

What am I doing wrong?

GalleyWest
  • 59
  • 1
  • 4

3 Answers3

2

You need to move your setTimeout to inside of the for loop

function iterator() {
  var y = 0;
  for (var t=0; t<newComp.slice(0, numTurn).length; t++) {
setTimeout(function() {
        glow(squareArr[newComp[t]].div) 
       y = y + 1
},500);
      }
Phil
  • 4,029
  • 9
  • 62
  • 107
  • I have changed to this, and now it only flashes the last item in the array. This leads me to believe the problem may be elsewhere then. – GalleyWest Jul 02 '17 at 04:05
1

Basically you want to schedule (using setTimeout) a set of functions which capture the index of each square, 500 msec apart to highlight the square.

function iterator() {
    for (let t=0; t<newComp.slice(0, numTurn).length; t++) {
        setTimeout(function() {
             glow(squareArr[newComp[t]].div) 
        }, 500 * t)
    }
}

uses the let keyword to capture the value of t in the lexical scope record of the nested function which calls glow. If you want to reinstate the y variable go ahead - it just seems to have the same value as t.

Usage of let is important. See the frequently asked question JavaScript closure inside loops – simple practical example for ways of capturing the value of loop variables within a closure without using let.

traktor
  • 17,588
  • 4
  • 32
  • 53
0

That is because everytime the glow() function is called, a new instance of the anonymous function() is created which is completely different from the previous instance, it so happens that just when the timeout of instance x of the anonymous function finishes, instance y also completes, which means you have newComp.slice(0, numTurn).length anonymous functions each with their own timeout of 500ms creating a very fast glow.

Suraj S
  • 1,019
  • 7
  • 18