简体   繁体   中英

Why is the JavaScript console saying my variable is undefined, even when I defined it two lines before?

I'm using WebSockets to connect to a remote host, and whenever I populate realData and pass it to grapher() , the JavaScript console keeps telling me realData is undefined. I tried checking the type of the data in the array, but it seems to be fine. I've called grapher() before using an array with random data, and the call went through without any problems. With the data from the WebSocket, however, the call will always give me "error: realData is not defined". I'm not sure why this is happening. Here is the code I used:

current.html:

var command = "Hi Scott"

getData();

function getData()
 { 
    console.log("getData is called");

    if("WebSocket" in window)
    {
            var dataCollector = new WebSocket("ws://console.sb2.orbit-lab.org:6100",'binary');
            dataCollector.binaryType = "arraybuffer";
            console.log(dataCollector.readyState);        

            dataCollector.onopen = function()
            {
                    //alert("The WebSocket is now open!");                  

                    console.log("Ready state in onopen is: " + dataCollector.readyState);


                    dataCollector.send(command);
                    console.log(command + " sent"); 
            }

            dataCollector.onmessage = function(evt)
            {


                            console.log("onmessage is being called");
                            var realData = new Uint8Array(evt.data);
                            console.log(realData);
                            grapher(realData); //everything up to this point works perfectly.
            }

            dataCollector.onclose = function()
            {
                    alert("Connection to Server has been closed");
            }


            return (dataCollector);
    }
    else
    {
            alert("Your browser does not support WebSockets!");
    }

}

graphing.js:

function grapher(realData)
{
            console.log("grapher is called");
            setInterval('myGraph(realData);',1000); //This is where the error is. I always get "realData is not defined".

}

function myGraph(realData)
{
            /*
           for(var i = 0; i < SAarray.length; i++) // Loop which will load the channel data from the SA objects into the data array for graphing.
            {
                    var data[i] = SAarray[i];
            }
            */
            console.log("myGraph is called");

            var bar = new RGraph.Bar('channelStatus', realData);
            bar.Set('labels', ['1','2','3','4','5','6','7','8']);
            bar.Set('gutter.left', 50);
            bar.Set('gutter.bottom', 40);
            bar.Set('ymax',100);
            bar.Set('ymin',0);
            bar.Set('scale.decimals',1);
            bar.Set('title','Channel Status');
            bar.Set('title.yaxis','Status (1 is on, 0 is off)');
            bar.Set('title.xaxis','Channel Number');
            bar.Set('title.xaxis.pos',.1);
            bar.Set('background.color','white');
            bar.Set('colors', ['Gradient(#a33:red)']);
            bar.Set('colors', ['red']);

            bar.Set('key',['Occupied','Unoccupied']);

            bar.getShapeByX(2).Set('colors',barColor(data[0]));


            bar.Draw();


}

Because strings (as code) passed to setInterval execute in the global scope, therefore the realData parameter isn't available. There's rarely a good reason to pass a string to setInterval . Instead, use:

setInterval(function () {
    myGraph(realData);
}, 1000);

Reference:

Try it without it needing to evaluate a string:

setInterval(function() {
    myGraph(realData);
},1000);

Any time you are using setTimeout or setInterval , you should opt for passing an actual function instead of a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM