javascriptarraysgm-xmlhttprequest

Array loses its contents after exiting xmlhttpRequest


I know that is a stupid question but i want to ask how i can save content to an array inside a xmlhttpRequest and use them after.

onlinestatus = new Array(count);
for (var i = 0; i <= count; i++) {
    GM_xmlhttpRequest({
        method: 'GET',
        url: 'http://www.website.com/player/' + player[i] + '/details.php',
        onload: function(responseDetails) {
            buddypage = jQuery(responseDetails.responseText);
            online = jQuery("span#OnlineStatus", buddypage);
            onlinestatus[i] = online.text();
        }
    });
    GM_log("Current: " + onlinestatus[i]);
}​

Solution

  • Two things will stop this working: the web request will be asynchronous, and the values will all be stored in the same location in the array.

    Here's the order things will happen, assuming count = 2:

    1. Set i = 0
    2. Check, i < count, is true, continue for loop
    3. Web request A starts
    4. Print result[0]
    5. Set i = 1
    6. Check, i < count, is true, continue for loop
    7. Web request B starts
    8. Print result[1]
    9. Set i = 2
    10. Check, i < count, is false, exit for loop
    11. ... time passes ...
    12. Web request A completes, sets result[i], so set result[2] = "foo"
    13. Web request B completes, sets result[i], so set result[2] = "bar"

    That means that the result array ends up as [undefined, undefined, "bar"]. The last value of the array could be foo or bar, depending on which web request finishes first. Either way, by the time the web requests complete, i will have already been set to the wrong value, and the results will have already been logged, so it will look like the results array is empty.