I’m trying to execute a setTimeout() function inside of a for loop in Javascript, but I am getting the error “shape is undefined”, even though it is defined, and I’m passing that as a parameter in the function within the setTimeout() call. The function works just fine if I delete the setTimeout enclosure.
Why am I getting this error and how can I fix it?
Thanks!
function fadeShapes(layer, movement, opacity, speed) {
var shapes = layer.getChildren();
for(var n = 0; n < shapes.length; n++) {
var shape = layer.getChildren()[n];
setTimeout(function(shape){
shape.transitionTo({
alpha: opacity,
duration: speed
});
}, 100);
}
}
JavaScript does not have block scope so all of your timeout functions are pointing at the same variable
shape, which after the loop finishes points to an undefined index of your array. You can use an anonymous function to emulate the scope you’re looking for:As you could tell by my issues getting the brackets matched up, this can be a little tricky. This can be cleaned up with ES5’s
Array.forEach:forEachis built into modern browsers but can be shimmed inInternet Explorerolder browsers.