When functions are called, JavaScript variables can sometimes disappear within them

Currently, I am facing an issue within my Google Maps code that is actually stemming from an architectural problem. Due to a high volume of requests, Google Maps sometimes limits the response, prompting the need for an additional request with a delay. However, when I try to call function2 again in this scenario, it returns an error stating "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);
        });
    }

}

Answer №1

One reason this is happening is because when you include a string of code with setTimeout(), it runs in the global scope where variables like array and i are not recognized. Even if i was accessible, its value may no longer be valid at that point.

A solution to this issue is to enclose the function code within an anonymous function as shown below:

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

By using this method, you avoid any discrepancies caused by changes in the i variable, allowing you to reuse start and end.

Additionally, it might be beneficial to serialize your Google requests, processing them one after the other to prevent rate limit problems.

Answer №2

The setTimeout function runs in a different scope than the scope containing your array variable. To address this, you can enclose it within an anonymous function.

For more information, check out: How can I pass a parameter to a setTimeout() callback?

Your modified code should look like this:

   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);
            }
        });

Note that your code was missing braces {} for the if-elseif statement. I have added these for clarity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for finding group words within a div panel

Check out this interactive demo I created to demonstrate what I need help with. There are multiple panels containing words, each separated by a line break. I am trying to create a filter that will hide panels that do not match the words entered in the sea ...

Can anyone tell me what js stands for?

I stumbled upon this snippet of code and am curious about what it does. Is it some sort of array? test = {a: [1,0,0], b:[0,1,0], c:[0,0,1]}; If I wanted to access the array for A specifically, how would I do that? console.log(bases[a]); This results in ...

Having trouble converting an Amazon S3 function into promises with when/node

I'm having trouble with an AWS S3 asynchronous function and encountering a strange issue. Here is the code snippet: var s3 = new AWS.S3(); var when = require('when'); var nodefn = require('when/node'); var getObjectP = nodefn.lif ...

Conceal player controls for HTML videos on iOS devices

How can I hide the video player controls in Windows and Android, they are hidden but still visible on iOS. I have tried different methods but can't seem to hide them. Here is what it looks like on iOS: https://i.sstatic.net/Uwrg3.png Here is my code ...

Iframe displaying a blank white screen following the adjustment of document.location twice

I am in the process of developing a web application that I intend to integrate into my Wix website. The main components of the required web application are a text screen and a button to switch between different screens/pages (html content). However, I am ...

Utilizing Angular 2+ with the [innerHTML] property to incorporate HTML with added style attributes

I am currently utilizing Angular 2+ [innerHTML] input for inserting HTML formatting that includes style tags. Within my template, the code looks like this: <span [innerHTML]="someVar"></span> In the component file, I have defined: someVar = ...

The webpage does not display the updated information from the controller after the Ajax call

Learning the ropes of MVC, I delved into creating a post method for showcasing fresh data post a datepicker selection in jquery. The jquery functionality is up and running smoothly, allowing me to iterate through the new data in the view. However, when i ...

How can MongoDB be used to query nested JSON structures?

My JSON data structure is as follows: "marks":{ "sem1" :{ "mark1":10, "total":100 }, "sem2":{ "mark2":20, "total":200 }, "sem3":{ "mark2":30, "total":300 } } I want to display the re ...

Should React.cloneElement be used to pass new children or copy props.children?

I am having trouble understanding the third parameter "children" of React.cloneElement and how it relates to this.props.children. After reading a helpful guide on higher order components, I implemented the following code: render() { const elementsTre ...

Utilizing Google Maps with WebGL to place multiple GLTF objects on a vector map based on geographical coordinates

Trying to incorporate 3D objects onto a Google Map overlay view using Three.js The main goal is to display bus stations using 3D objects with specific longitudes and latitudes Attempted to use the '@googlemaps/three' 'latLngAltitudeToVecto ...

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

Updating AngularJS views based on window resizing

I've been working on an Angularjs application and everything is running smoothly, but I'm facing challenges when it comes to implementing a mobile version of the site. Simply using responsive styles won't cut it; I need to use different view ...

Using conditional statements like 'if' and 'else' in JavaScript can

Can someone help me with solving my problem using if-else statements in Javascript? I need to filter names by gender and save them as keys - woman / man in local storage. Any assistance would be greatly appreciated. I am struggling to figure out how to im ...

Are $(function() { }) and $(document).ready(function() { }) the same function under the hood?

Similar Question: What sets apart these jQuery ready functions? Do $(function(){}); and $(“document”).ready(function(){}); have the same meaning? Beginning javascript code with $(function, etc. This day, as I was examining some jav ...

Transfer data to the local context of JavaScript functions

My usual approach involves using a structure similar to this: var $this, url, callback; //private variables loadCallback = function($that, url, callback) { return function(responseText, textStatus, req) { ... }; })($this, url, callback) H ...

Program that duplicates text to clipboard upon clicking on the text

Hey there, I have a query regarding the script provided below: function copyElementText(id) { var text = document.getElementById(id).innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); ...

Your search parameter is not formatted correctly

I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example: http://localhost:3000/patient?filter=name:jack I have implemented a method to retrieve and convert these ...

Toggle menu visibility when body is clicked

<script> $(".bg").on('click', function(e) { e.preventDefault(); $("#navMenu").removeClass('open'); $("#searchBar").removeClass('active'); }); </script> My goal is to togg ...

Is it possible to adjust the zoom on my website so that it adapts to the user's higher resolution if my website layout is initially set for 800x600 resolution?

Apologies for the confusion in my previous question. I am not looking to alter the user's browser settings but rather focus on optimizing my website layout for the most common resolution size. Ideally, I want my page to adjust and zoom in if the user& ...

Steps for launching a browser using Capybara and Selenium

I am completely new to utilizing Capybara and have not had any experience with Selenium in the past. Currently, I am working on a Ruby on Rails project on MacOSX and encountering an issue where the browser window does not open when I execute my test. My te ...