0

I'm having a bit of a problem regarding global variables in that when I hit this block of code:

if(done === true){
    console.log(songList);
}

the values of done and songList are now gone, however if I output them with console.log immediately after assign done=true then they carry the expected values (songList is built up in the function run by the eval statement). Can anyone explain why this is?

var song = {name:"", price:"", artist:"", image:""};
var done = false;
var songList = [];

function runJSON(network,searchType){
    var URL     = returnURL(network,searchType,$('#song_field').val().split(' ').join("+"));

    $.getJSON(URL, function(data){
        if(document.getElementById("box") !== "undefined"){
            clearScreen();
            createCols();
        }

        eval(network + "(data);");
        done = true; 

    });

    if(done === true){
        console.log(songList);
    }
}
Kim Ward
  • 142
  • 1
  • 10
  • yes, this is explained by the fact that `$.getJSON` is an asynchronous function – Igor Nov 11 '14 at 17:04
  • What you mean by *lost*, did it keep the value `false` or it becomes `undefined` ? Because the log function will show its value **before** it gets changed by the `getJSON` callback, because it is *async*... – DontVoteMeDown Nov 11 '14 at 17:05

1 Answers1

0

done = true is getting assigned in the callback from $.getJSON. So it will actually run after you test for if(done === true).

More about $.getJSON is here http://api.jquery.com/jquery.getjson/ - notice that 'success' is a callback.

If you did:

function runJSON(network,searchType){
    var URL     = returnURL(network,searchType,$('#song_field').val().split(' ').join("+"));

    $.getJSON(URL, function(data){
        if(document.getElementById("box") !== "undefined"){
            clearScreen();
            createCols();
        }

        eval(network + "(data);");
        done = true; 

        if(done === true){
            console.log(songList);
        }
    });
}

Then you would see the songlist

CambridgeMike
  • 4,562
  • 1
  • 28
  • 37