0

Im wondering why this function is returning this error:

Uncaught ReferenceError: capasPlay is not defined at funPlay.handleFunPlay

funPlay.prototype.handleFunPlay = function handleFunPlay() {
        
        capasPlay = [capa4_48R, capa4_49R, capa4_50R, capa4_51R, capa4_52R, capa4_53R, capa4_54R, capa4_55R, capa4_56R];

        
        var index;
        
        for (index=0; index <= capasPlay.leght; index++){
            
            window.setTimeout(function(){capasPlay[index].setVisible(false)}, 1000);
        }
    };
    return funPlay;

The array is made from variables like this:

var capa4_48R = new TileLayer({
                source: new TileWMS({
                    url: 'http://localhost:8080/geoserver/wms',
                    params: { 'LAYERS': 'earth:4_48R', 'TILED': true },
                    serverType: 'geoserver',
                })
});

Thanks a lot!

JTravol
  • 1
  • 1
  • 1
    Nowhere in the code you've posted tries to read a property called `X`. Please provide a [mcve] demonstrating the problem you're having. At very least the error _might_ come from `setVisible` method, so perhaps show us that, – Jamiec Sep 30 '20 at 15:41
  • sorry man. You are right. The error is: Uncaught ReferenceError: capasPlay is not defined at funPlay.handleFunPlay – JTravol Sep 30 '20 at 15:45
  • error is pretty clear, where are you defining capasPlay? – Nonik Sep 30 '20 at 15:47
  • Here is the definition of the array: – JTravol Sep 30 '20 at 15:48
  • capasPlay = [capa4_48R, capa4_49R, capa4_50R, capa4_51R, capa4_52R, capa4_53R, capa4_54R, capa4_55R, capa4_56R]; – JTravol Sep 30 '20 at 15:48

2 Answers2

1

If you are not using vanilla Javascript, you need to explicitly define variables with a var, const or let.

const capasPlay = [ ... ]
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
  • I have defining it as a const but the same error happening. Maybe the "setTimeout" function is not working with the iteration. Maybe it wasnt thought to work like that. Not sure. Thank you friend – JTravol Sep 30 '20 at 16:04
0

I'm assuming that you replaced whatever property you're actually calling with "X"?

I see an issue with your loop which would cause an undefined property error. index will be out of range when the function triggered by setTimeout is called. To fix this, you need to save a copy of the current index for each iteration of the loop.

for (index=0; index <= capasPlay.leght; index++){
    const i = index;
    window.setTimeout(function(){capasPlay[i].setVisible(false)}, 1000);
}

Update

As suggested in setTimeout in for-loop does not print consecutive values, there is a better solution that I was not aware of.

for (let index=0; index <= capasPlay.leght; index++){
    window.setTimeout(function(){capasPlay[index].setVisible(false)}, 1000);
}
Matt
  • 171
  • 1
  • 2