TSkora
TSkora

Reputation: 75

javascript variable gets lost inside functions

I am dealing with this problem in my google maps code but its actually an architectural problem. at some point because of so much request google maps limits the response, and at that point i want to make another request with a delay, but when i call function2 again it says "array is not defined".

function1() {
    var array = JSON.parse(xmlhttp.responseText);

    for (i; i < length; < i++) {
        function2(array[i].one, array[i].two);
    }

    function3() {
        //render directions
    }

    function2(start, end) {
        directionsService.route({
            origin: start,
            destination: end,
        },

        function (result, status) {
            if (status == google.maps.DirectionsStatus.OK)
                function3(result);
            else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
                var functionStr = "function2(array[i].one" + ',' + "array[i].two)";
            setTimeout(functionStr, 5000);
        });
    }

}

Upvotes: 0

Views: 227

Answers (2)

p0wl
p0wl

Reputation: 481

The function in your setTimeout is executed in a seperate scope, not within the scope with your array variable. You can wrap it in an anonymous function.

See here: How can I pass a parameter to a setTimeout() callback?

So your code would be:

   function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                function3(result);
            } else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                setTimeout(function () {
                    function2(array[i].one, array[i].two);
                }, 5000);
            }
        });

Please have in mind that your code is missing braces {} for your if elseif statement. I've added these.

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173652

That's because when you use a string of code with setTimeout() it gets executed in the global scope, which doesn't know about array. The global scope would also not know about i; even if it did, the value of i is already no longer valid anyway.

It should work if you wrap the function code in an anonymous function, like this:

setTimeout(function() {
    function2(start, end);
}, 5000);

Please note that you can simply reuse start and end here, because those values have been protected against changes in the i variable.

Btw, you could consider serializing all your Google requests, i.e. one request after the other to prevent those rate issues.

Upvotes: 6

Related Questions