2

I have the following being invoked inside a $(document).ready(function() { ... });

var serviceIcons = $('#services-row img');
for (var k = 0, n = serviceIcons.length; k < n; ++k) {
    setTimeout(function () { 
        $(serviceIcons[k]).css('transform', 'none'); 
    }, k * 50);
}

and I've verified that $('#services-row img') is returning the correct set of objects, but I'm not seeing the attribute style="transform:none;" on the img applied to the imgs. The corresponding CSS is:

#services-row img { 
    transform: translateX(-10000px) translateY(-10000px); 
    transition: transform 1s; 
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Subpar Web Dev
  • 3,210
  • 7
  • 21
  • 35

1 Answers1

3

By the time the timeout function is called, the k variable has already finished looping, and it will always be equal to serviceIcons.length within the function.

To access the loop value, use this syntax instead:

setTimeout(
  function(k) {
    return function() {
      ...
    }
  }(k), k * 50
);

So your final code would be:

var serviceIcons = $('#services-row img');
for(var k = 0, n = serviceIcons.length; k < n; ++k) {
  setTimeout(
    function(k) {
      return function() {
        $(serviceIcons[k]).css('transform', 'none');
      }
    }(k), k * 50
  );
}

See http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside for a good description of this solution.

Fiddle

Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79