Reputation: 445
I have the following code
for (var i = 1; i<=10; i++){
temp = "resp.items[" + (i-1).toString() + "].snippet.thumbnails.medium.url";
thumbnail = '<img src="' + eval(temp) + '">';
$("#yt_" + i.toString()).append("<a href='#'>" + thumbnail + "<br>" + resp.items[i-1].snippet.title + "</a>");
if(typeof (resp.items[i-1].contentDetails.upload) != 'undefined')
ytid = resp.items[i-1].contentDetails.upload.videoId;
else if(typeof (resp.items[i-1].contentDetails.recommendation) != 'undefined')
ytid = resp.items[i-1].contentDetails.recommendation.resourceId.videoId;
else
ytid = resp.items[i-1].contentDetails.playlistItem.resourceId.videoId;
newurl = "https://gdata.youtube.com/feeds/api/videos/" + ytid +"?v=2&alt=jsonc&callback=?";
console.log("i is " + i);
//The following is executed after the loop finishes
$.getJSON(newurl, function (dur) {
duration_reco = dur.data.duration;
data[i-1] = {
"logo" : "logos/youtube_vsmall.png",
"video_low" : "",
"thumb" : resp.items[i-1].snippet.thumbnails.medium.url,
"title" : resp.items[i-1].snippet.title.substring(0,15) + '...' + secondsToHms(duration_reco),
"author" : "koustubh",
"tags" : ["1","2","3"],
"themes" : ["1","2","3"],
"link" : "playVideo?vid=" + ytid + "&service=youtube"
};
});
}
I just found out that the $.getJSON
function executes after completing the entire for loop. What can I do to make it wait and execute and follow the code order.
Upvotes: 0
Views: 56
Reputation: 12127
You should use $.ajax({...})
so you can add {async:false}
in parameters
Like
$.ajax({
url : "xyz.php",
async : false,
dataType : json
success : function(data){
//code here
}
});
You can also add {async:false}
globally.
NOTE: This will work with all ajax function that define on page
$.ajaxSetup({async:false});
Upvotes: 1