dbmitch dbmitch - 14 days ago 5x
Javascript Question

jQuery - using global array and wait for $get to load retrieved data?

Been struggling all day with looking at code examples and can't get this to work.

Basically I want to load an array using the HTML from four local files.
Then I'll use that HTML to fill a div dynamically with some kind of animated slider.

My problem is that I can't seem to get the timer to wait for the html to be retrieved and assigned to the variables. The GET is working great, but the variables don't seem to be loaded outside the GET loop.

I can see the asynch GET filling the array properly, but the elements remain undefined in the loop. I think they're global variables so it shouldn't be that.

I'm new at jQuery and have been using SO for examples, so open to any suggestions - hopefully this is just an obvious fix for an experienced javascript coder.

Here's my code:

window.standings = new Array(4);
window.iURL = 0;

standingsURL = ["MondayNight.html", "TuesdayNight.html", "WednesdayNight.html", "ThursdayNight.html"]

for (window.iURL = 0; window.iURL < window.standings.length; window.iURL ++) {
$.get(standingsURL[window.iURL], function( data ) {
window.standings[window.iURL] = data;
alert (window.standings[window.iURL]);
}, "text");

setTimeout(function repeatTimeout() {
if(window.standings[window.standings.length] !== undefined){
for (window.iURL = 0; window.iURL < window.standings.length; window.iURL ++) {
alert (window.standings[window.iURL]);
} else {
alert ("Wait again");
setTimeout(repeatTimeout, 2500);
}, 1000);


The first issue I can see is that in your repeatTimeout function, you're referencing an item in your array that doesn't exist.


which is equivalent to window.standings[4]

You have an array with four items in it, and you're referencing array index 4 here - but arrays are zero-indexed, so only indexes 0, 1, 2, and 3 are valid. Try:

window.standings[window.standings.length - 1]


Declare an empty array:

window.standings = []

Instead of: window.standings[window.iURL] = data;, do this:


Your if function now checks for length:

if(window.standings.length === 4)

This is a relatively crude solution. Check out this SO post for more information about the when function.