Search code examples
javascriptjquerygetjsonconsole.log

for variable within .getJSON displayed wrong


I have the following code (javascript/jQuery)

$(function(){
    for(var i=0;i<3;i++){

        $.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data){
            console.log(i);
            console.log(data);
        });
    }
});

console log:

3
Object { stream: Object, _links: Object }
3
Object { stream: Object, _links: Object }
3
Object { stream: Object, _links: Object }

isn't it true, that console.log(i); should log 0 in the first loop, 1 in the second and 2 in the third? But somehow it always returns 3 :(


Solution

  • Try this

    $(function(){
        for(var i=0;i<3;i++){
            (function (index) {
                $.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data) {
                    console.log(index);
                    console.log(data);
                });
            })(i)
        }
    });