Based on chrome developer tools a breakpoints I think I’m dealing with a scope issue I can figure out. Is it the way I define the function? The script below is an include js file and the array ‘ timeStamp I want available for use in other functions without having to call my loadData function everytime.
The timeStamp array goes undefined once it leaves the for loop before it even leaves the function.
var timeStamp = []; // Want this array to be global
function loadData (url){
$.getJSON(url, function(json) {
for (var i=0;i<json.length;i++){
timeStamp.push(json[i].TimeStamp);
}
console.log(inputBITS); //returns the value
});
console.log(inputBITS); //undefined
}
Thank you for anyhelp
It looks like the issue is that
getJSONis asynchronous. When it executes and finishes and your code continues on, it indicates only the START of the networking operation to retrieve the data. The actual networking operation does not complete until some time later.When it does complete, the success handler is called (as specified as the second argument to your
getJSON()call) and you populate thetimeStamparray. ONLY after that success handler has been called is thetimeStamparray valid.As such, you cannot use the
timeStamparray in code that immediately follows thegetJSON()call (it hasn’t been filled in yet). If other code needs thetimeStamparray, you should call that code from the success handler or use some other timing mechanism to make sure that the code that uses thetimeStamparray doesn’t try to use it until AFTER the success handler has been called and thetimeStamparray has been populated.It is possible to make some Ajax calls be synchronous instead of asynchronous, but that is generally a very bad idea because it locks up the browser during the entire networking operation which is very unfriendly to the viewer. It is much better to fix the coding logic to work with asynchronous networking.
A typical design pattern for an ajax call like this is as follows: