The function below is supposed to grab videos for each query and construct some html that depends on i
function getVideos() {
var text = "";
for(var i=0; i<queryArray.length; i++){
var queryUrl = "http://gdata.youtube.com/feeds/api/videos?q="+queryArray[i]+
"&max-results=1&orderby=relevance&v=2&alt=json&format=5";
$.get(queryUrl, function(data){
constructHtml(data, i);
}, 'json');
}
}
however it is passing i as 2 to constructHtml everytime $.get is called why’s that?
Note: There are two values in querryArray and so "2" is technically out of bounds.
Because of the default asynchronous nature of
$.get()your for loop continues executing and your i variable gets reassigned.The quick way to fix this is to set
async: falseon your$.get()this will essentially prevent your for loop from continuing its execution until your$.get()has completed meaning yourivalue wont change in the process.It must be emphasised though that this will prevent all scripts executing on the page until your for loop has finished, potentially locking your users out from completing other actions for an extended period of time.